[英]How to show ModelState.AddModelError when the Model is Empty in MVC4
I am displaying a shopping cart. 我正在显示购物车。 I need to check for empty values in Shopping cart and display a message like "The Shopping Cart is empty". 我需要检查“购物车”中的空值,并显示“购物车为空”之类的消息。
When I use ModelState.AddModelError in myAction, it throws an exception as there is null reference in Model. 当我在myAction中使用ModelState.AddModelError时,它会引发异常,因为Model中没有空引用。 How to display the ErrorMessage. 如何显示错误消息。
My Action 我的行动
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();
}
My 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>
}
Any suggestions. 有什么建议么。
The problem is your not passing an empty model in when there is nothing in the cart therefore your ModelState
has nothing to attach itself to. 问题是,当购物车中没有东西时,您不会传递空模型,因此您的ModelState
没有任何附加条件。 However, it doesn't make sense to treat this as an error , it's perfectly valid for the shopping cart to be empty. 但是,将其视为错误是没有意义的,对于购物车为空是完全有效的。 Instead, I would handle the empty model in your view directly eg 相反,我将直接在您的视图中处理空模型,例如
Action 行动
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());
}
View 视图
@model IList<CardModel>
@if (Model.Count > 0)
{
...
}
else
{
<p>Your shopping cart is empty!</p>
}
像这样更改操作中的最后一行:
return View(new List<CartModel>());
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.