【问题标题】:How to show ModelState.AddModelError when the Model is Empty in MVC4当模型在 MVC4 中为空时如何显示 ModelState.AddModelError
【发布时间】:2012-10-29 10:58:15
【问题描述】:

我正在展示一个购物车。我需要检查购物车中的空值并显示“购物车为空”之类的消息。

当我在 myAction 中使用 ModelState.AddModelError 时,它会引发异常,因为 Model 中有空引用。如何显示错误消息。
我的行动

  public ActionResult Index()
        {
            string id = Request.QueryString["UserID"];
            IList<CartModel> objshop = new List<CartModel>();
            objshop = GetCartDetails(id);
            if (objshop.Count > 0)
            {
                return View(objshop.ToList());
            }
            else
            {
                ModelState.AddModelError("", "Your Shopping Cart is empty!");
            }
            return View();
}

我的观点

    @{
         @Html.ValidationSummary(true)
     }

 <th > @Html.DisplayNameFor(model => model.ProductName) </th>
 <th > @Html.DisplayNameFor(model => model.Quantity)   </th>
 <th > @Html.DisplayNameFor(model => model.Rate)      </th>
 <th > @Html.DisplayNameFor(model => model.Price)    </th>        
 @foreach (var item in Model)
   {
<td>  @Html.DisplayFor(modelItem => item.ProductName)</td>
<td>  @Html.DisplayFor(modelItem => item.Quantity)</td>
<td>  @Html.DisplayFor(modelItem => item.Rate) </td>
<td>  @Html.DisplayFor(modelItem => item.Price) </td>
   }

任何建议。

【问题讨论】:

    标签: c# asp.net asp.net-mvc asp.net-mvc-3


    【解决方案1】:

    问题是当购物车中没有任何东西时你没有传递一个空模型,因此你的ModelState 没有任何东西可以附加到它自己。但是,将其视为错误是没有意义的,购物车为空是完全有效的。相反,我会直接处理您视图中的空模型,例如

    动作

    public ActionResult Index()
    {
        string id = Request.QueryString["UserID"];
        IList<CartModel> objshop = new List<CartModel>();
        // assuming GetCartDetails returns an empty list & not null if there is nothing
        objshop = GetCartDetails(id);
        return View(objshop.ToList());
    }
    

    查看

    @model IList<CardModel>
    
    @if (Model.Count > 0)
    {
        ...
    }
    else
    {
        <p>Your shopping cart is empty!</p>
    }
    

    【讨论】:

      【解决方案2】:

      像这样更改 Action 中的最后一行:

      return View(new List<CartModel>());
      

      【讨论】:

        猜你喜欢
        • 2017-06-29
        • 1970-01-01
        • 1970-01-01
        • 2021-01-12
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-03-08
        • 1970-01-01
        相关资源
        最近更新 更多