kk1076
kk1076

Reputation: 1748

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. 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.

Upvotes: 0

Views: 3052

Answers (2)

James
James

Reputation: 82096

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. 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 e.g.

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>
}

Upvotes: 3

Stefan P.
Stefan P.

Reputation: 9519

Change the last line in your Action like this:

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

Upvotes: 1

Related Questions