我有一个视图,我想对表中每一行中的项目执行不同的操作,类似于此(例如,~/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>
<% } %>
在我的ThingController
中,我具有类似于以下的功能:
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");
}
在大多数情况下,这工作正常。问题是如果ThingService.SetEnabled
抛出错误,我希望能够在表格顶部显示错误。我Html.ValidationSummary()
在页面中尝试了一些东西,但我无法让它工作。
请注意,我不想将用户发送到单独的页面来执行此操作,并且我正在尝试在不使用任何 javascript 的情况下执行此操作。
我打算以最好的方式展示我的桌子吗?如何以我希望的方式显示错误?我最终会在页面上得到大约 40 个小表格。这种方法主要来自这篇文章,但它并没有以我需要的方式处理错误。
有接盘侠吗?
感谢@Shaharyar 解决:
public ActionResult Manage() {
if (TempData["Error"] != null)
ModelState.AddModelError("", TempData["Error"] as string);
return View(ThingService.GetThings());
}
[HttpPost]
public ActionResult SetEnabled(string x, bool enable) {
try {
ThingService.SetEnabled(x, enable);
} catch (Exception ex) {
TempData["Error"] = ex.Message;
}
return RedirectToAction("Manage");
}
然后只是我表格顶部的 ValidationSummary 的一个小表格。
<% using (Html.BeginForm()) { %>
<%: Html.ValidationSummary(false) %>
<% } %>
谢谢!