【发布时间】:2010-06-11 14:36:29
【问题描述】:
我有一个视图,我想对表中每一行中的项目执行不同的操作,类似于此(例如,~/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 个小表格。这种方法主要来自this 文章,但它并没有以我需要的方式处理错误。
有接受者吗?
感谢@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) %>
<% } %>
谢谢!
【问题讨论】:
标签: asp.net asp.net-mvc asp.net-mvc-2 asp.net-4.0