显示模型状态错误

lea*_*ing 9 asp.net-mvc-3

我有以下代码,但错误causght没有显示.怎么了 ?

  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);
        }
    }
Run Code Online (Sandbox Code Playgroud)
    @model MvcUI.Models.RateGroupListModel

@{
    View.Title = "RateGroup";
    Layout = "~/Views/Shared/_Layout.cshtml";
}

<h2>Rate Group</h2>

@Html.ValidationSummary()

@using (Html.BeginForm())
Run Code Online (Sandbox Code Playgroud)
    private ActionResult GetIndexView(RateGroupListModel model)
    {
       return View("RateGroup", model);
    }

    public ActionResult RateGroup(RateGroupListModel model)
    {
       return GetIndexView(model);
    }
Run Code Online (Sandbox Code Playgroud)

Jam*_*ail 13

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

通常,您只需直接从DeleteRateGroup操作渲染RateGroup视图,而无需重定向,如果需要,可以传入模型,如下所示:

return View("RateGroup", model);
Run Code Online (Sandbox Code Playgroud)

如果您希望ModelState与您一起进行第二个操作,请查看MvcContrib的ModelStateToTempDataAttribute.这是属性的描述,来自MvcContrib源代码的注释:

从操作返回RedirectToRouteResult时,ViewData.ModelState字典中的任何内容都将复制到TempData中.从操作返回ViewResultBase时,先前复制到TempData的任何ModelState条目都将被复制回ModelState字典.