Asp.net mvc 3 显示模型状态错误
我有下面的代码,但是没有显示错误。怎么了Asp.net mvc 3 显示模型状态错误,asp.net-mvc-3,Asp.net Mvc 3,我有下面的代码,但是没有显示错误。怎么了 public ActionResult DeleteRateGroup(int id) { try { RateGroup.Load(id).Delete(); RateGroupListModel list = new RateGroupListModel(); return GetIndexView(list); }
public ActionResult DeleteRateGroup(int id)
{
try
{
RateGroup.Load(id).Delete();
RateGroupListModel list = new RateGroupListModel();
return GetIndexView(list);
}
catch (Exception e)
{
RateGroupListModel model = new RateGroupListModel();
if (e.InnerException != null)
{
if (e.InnerException.Message.Contains("REFERENCE constraint"))
ModelState.AddModelError("Error", "The user has related information and cannot be deleted.");
}
else
{
ModelState.AddModelError("Error", e.Message);
}
return RedirectToAction("RateGroup", model);
}
}
看起来您正在设置ModelState错误,然后重定向到另一个操作。我敢肯定,当你这么做的时候,ModelState会迷失方向 通常,您只需直接从DeleteRateGroup操作呈现RateGroup视图,而无需重定向,在需要时传入模型,如下所示:
return View("RateGroup", model);
如果希望ModelState与您一起执行第二个操作,请查看MvcContrib的ModelStateToTempDataAttribute。以下是MvcContrib源代码注释中的属性描述:
从操作返回RedirectToRouteResult时,ViewData.ModelState字典中的任何内容都将复制到TempData中。从操作返回ViewResultBase时,以前复制到TempData的所有ModelState条目都将复制回ModelState字典
private ActionResult GetIndexView(RateGroupListModel model)
{
return View("RateGroup", model);
}
public ActionResult RateGroup(RateGroupListModel model)
{
return GetIndexView(model);
}
return View("RateGroup", model);