How to show ModelState.AddModelError when the Model is Empty in MVC4
- by kk1076
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. 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.