How to show ModelState.AddModelError when the Model is Empty in MVC4

Posted by kk1076 on Stack Overflow See other posts from Stack Overflow or by kk1076
Published on 2012-10-29T10:58:15Z Indexed on 2012/10/29 11:00 UTC
Read the original article Hit count: 260

Filed under:
|
|
|

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.

© Stack Overflow or respective owner

Related posts about c#

Related posts about ASP.NET