0

我有一个视图,我想对表中每一行中的项目执行不同的操作,类似于此(例如,~/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) %>
<% } %>

谢谢!

4

2 回答 2

0

尝试做:

 try {
    ThingService.SetEnabled(x, enable);
  } catch (Exception ex) {
    ModelState.AddModelError("", ex.Message); // I know this is wrong...
    return View(); //return to the view to display the error
  }

如果您返回错误的同一个视图,它会重新加载该视图;您可能需要重新加载一些数据项,但错误地返回视图,然后框架应该从 ModelState 中提取这些错误并显示它们。

最有效的方法是使用 JQuery 将表单提交到服务器,这样您就不必总是重新加载页面,并在客户端显示消息。

HTH。

于 2010-06-11T15:26:07.897 回答
0

咱们试试吧...

有一TempData本字典可供您做这类事情。

而且您可能不得不依靠另一个页面来为您处理错误。

因为一旦 ViewModel 无法传递给 View 就会抛出异常。

但是如果模型有一些问题,你可以执行以下操作(只需将一个空模型传递给视图):

public SetEnabled(string x, bool enable) {
  try {
    ThingService.SetEnabled(x, enable);
    return View(viewModel);
  } catch {
    TempData["GetThingsError"] = "Oops! Some error happened while processing your request!"
    return View(); 
    /*
     * Note that you can also pass the initial model
     * back to the view -> this will do the model validation 
     * (specified in your model) 
     */
  }
  return RedirectToAction("Manage");
}

TempData 消息仅适用于当前请求,刷新后将消失。

它可能需要进一步调整,但这将是向用户/客户报告这种错误的方向。

于 2010-06-11T15:32:57.380 回答