asp.net-mvc-3 – 显示modelstate错误

前端之家收集整理的这篇文章主要介绍了asp.net-mvc-3 – 显示modelstate错误前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我有以下代码,但是错误causght没有显示.哪里不对 ?
  1. public ActionResult DeleteRateGroup(int id)
  2. {
  3. try
  4. {
  5. RateGroup.Load(id).Delete();
  6.  
  7. RateGroupListModel list = new RateGroupListModel();
  8. return GetIndexView(list);
  9. }
  10. catch (Exception e)
  11. {
  12. RateGroupListModel model = new RateGroupListModel();
  13.  
  14. if (e.InnerException != null)
  15. {
  16. if (e.InnerException.Message.Contains("REFERENCE constraint"))
  17. ModelState.AddModelError("Error","The user has related information and cannot be deleted.");
  18. }
  19. else
  20. {
  21. ModelState.AddModelError("Error",e.Message);
  22. }
  23. return RedirectToAction("RateGroup",model);
  24. }
  25. }
  1. @model MvcUI.Models.RateGroupListModel
  2.  
  3. @{
  4. View.Title = "RateGroup";
  5. Layout = "~/Views/Shared/_Layout.cshtml";
  6. }
  7.  
  8. <h2>Rate Group</h2>
  9.  
  10. @Html.ValidationSummary()
  11.  
  12. @using (Html.BeginForm())
  1. private ActionResult GetIndexView(RateGroupListModel model)
  2. {
  3. return View("RateGroup",model);
  4. }
  5.  
  6. public ActionResult RateGroup(RateGroupListModel model)
  7. {
  8. return GetIndexView(model);
  9. }

解决方法

看起来你正在设置ModelState错误,然后重定向到另一个操作.我确定当你这样做时,ModelState会丢失.

通常,您只需从DeleteRateGroup操作直接呈现RateGroup视图,而不需要重定向,如果需要,请传入模型,如下所示:

  1. return View("RateGroup",model);

如果您希望ModelState与您进行第二个操作,请查看MvcContrib的ModelStateToTempDataAttribute.这是属性的描述,从MvcContrib源代码的意见:

When a RedirectToRouteResult is returned from an action,anything in the ViewData.ModelState dictionary will be copied into TempData. When a ViewResultBase is returned from an action,any ModelState entries that were prevIoUsly copied to TempData will be copied back to the ModelState dictionary.

猜你在找的asp.Net相关文章