我正在展示购物车。我需要检查购物车中的空值并显示消息,如"购物车为空"。
当我在myAction中使用ModelState.AddModelError时,它会抛出异常,因为Model中有空引用。如何显示ErrorMessage
我的行动
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>
}
任何建议。
答案 0 :(得分:3)
问题是,当购物车中没有任何东西时,你没有传递空模型,因此你的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>
}
答案 1 :(得分:1)
更改Action中的最后一行:
return View(new List<CartModel>());