showing errors from actions in table-based views
- by enashnash
I have a view where I want to perform different actions on the items in each row in a table, similar to this (in, say, ~/Views/Thing/Manage.aspx):
<table>
<% foreach (thing in Model) { %>
<tr>
<td><%: thing.x %></td>
<td>
<% using (Html.BeginForm("SetEnabled", "Thing")) { %>
<%: Html.Hidden("x", thing.x) %>
<%: Html.Hidden("enable", !thing.Enabled) %>
<input type="submit"
value="<%: thing.Enabled ? "Disable" : "Enable" %>" />
<% } %>
</td>
<!-- more tds with similar action forms here, a few per table row -->
</tr>
<% } %>
In my ThingController, I have functions similar to the following:
public ActionResult Manage() {
return View(ThingService.GetThings());
}
[HttpPost]
public ActionResult SetEnabled(string x, bool enable) {
try {
ThingService.SetEnabled(x, enable);
} catch (Exception ex) {
ModelState.AddModelError("", ex.Message); // I know this is wrong...
}
return RedirectToAction("Manage");
}
In the most part, this is working fine. The problem is that if ThingService.SetEnabled throws an error, I want to be able to display the error at the top of the table. I've tried a few things with Html.ValidationSummary() in the page but I can't get it to work.
Note that I don't want to send the user to a separate page to do this, and I'm trying to do it without using any javascript.
Am I going about displaying my table in the best way? How do I get the errors displayed in the way I want them to? I will end up with perhaps 40 small forms on the page. This approach comes largely from this article, but it doesn't handle the errors in the way I need to.
Any takers?