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

前端之家收集整理的这篇文章主要介绍了asp.net-mvc-3 – 显示modelstate错误前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我有以下代码,但是错误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);
        }
    }
@model MvcUI.Models.RateGroupListModel

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

<h2>Rate Group</h2>

@Html.ValidationSummary()

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

    public ActionResult RateGroup(RateGroupListModel model)
    {
       return GetIndexView(model);
    }

解决方法

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

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

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.

原文链接:https://www.f2er.com/aspnet/245627.html

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