So I wanted to create a toggle-button for a table, where I can make an async call to update a database record (enable/disable).
After some trial and error, I have managed to get it working – but it feels like there must be a more elegant way.
- I don’t like repeating my image-tag in my controller, obviously… How can I avoid that in an elegant way?
- Is there an overall better way to approach this that what I have done?
Here is my code in the controller:
public ActionResult ToggleEnabled(int id)
{
if (Request.IsAjaxRequest())
{
var p = this.PageRepository.GetPage(id);
p.Enabled = p.Enabled != true;
this.PageRepository.Edit(p);
return p.Enabled ? Content("<img src='/Content/icons/tick.png' border=0 />") : Content("<img src='/Content/icons/tick_grey.png' border=0 />");
}
return Content("Error");
}
And the view…:
<% var img = Model.Enabled ? "tick.png" : "tick_grey.png"; %>
<% foreach (var item in Model)
{ %>
...
<td align="center">
<%=Ajax.ActionLink("[replacethis]",
"ToggleEnabled",
new { id = Model.ID },
new AjaxOptions { UpdateTargetId = "toggleimage" + Model.ID }).Replace("[replacethis]",
string.Format("<div id='toggleimage{0}'><img src='/Content/icons/{1}' border='0' alt='toggle'/></div>",
Model.ID, Model.Enabled ? "tick.png" : "tick_grey.png"))%>
</td>
...
<% } %>
The trick/hack with the Ajax.Actionlink using an image was found here.

How about rendering checkbox based on whether the model is enabled or not.
In jQuery, you can replace those checkboxes with your images. Something like
Your document.ready code may look like,
Alternatively, you can use plugin like jquery-checkbox to give them any fancy styling you may think of.