So, I wanted to create a switch button for a table where I can make an asynchronous call to update the database record (enable / disable).
img http://i41.tinypic.com/os4vua.jpg
After some trial and error, I managed to get it to work, but there seems to be a more elegant way.
- I don't like repeating my image tag in my controller, obviously ... How can I avoid this in an elegant way?
- Is there a better way to get closer to this that I did?
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>
...
<% } %>
Trick / hack with Ajax.Actionlink using image was found here .
source
share