0

I got this error after I hit the Delete from Cart, Object reference not set to an instance of an object. This is happening in my partial View. Any idea on how to resolve this ?

TableContent.cshtml (partial view) from Panier

 @model Tp1WebStore3.ViewModels.ShoppingCartViewModel

 @{
     ViewBag.Title = "Table Content";
 }

 <a href="#" class="TableContent">
     <table>
         <tr>
             <th>
                 Produit
             </th>
             <th>
                 Prix (unitaire)
             </th>
             <th>
                 Quantite
            </th>
            <th></th>
         </tr>
         @foreach (var item in Model.CartItems)    <=== error is happening here
         {
             <tr id="row-@item.ProduitId">
                 <td>
                     @Html.ActionLink(item.Produit.Description, "Details", "Produit", new { id = 
                         item.ProduitId }, null)
                 </td>
                 <td>
                     @item.Produit.Prix
                 </td>
                 <td id="item-count-@item.PanierId">
                     @item.Quantite
                 </td>
                 <td>
                     <a href="#" class="RemoveLink" data-id="@item.PanierId"> Enlever du panier 
                     </a>
                 </td>
             </tr>
         }
         <tr>
             <td>
                 Total
             </td>
             <td></td>
             <td></td>
             <td id="cart-total">
                 @Model.CartTotal
             </td>
         </tr>
     </table>
 </a>

Index.cshtml from Panier

 @model Tp1WebStore3.ViewModels.ShoppingCartViewModel

 @{
     ViewBag.Title = "Shopping Cart";
 }
 <script src="/Scripts/jquery-1.8.2.min.js" type="text/javascript"></script>

 <script type="text/javascript">
     $(function () {
         $('.RemoveLink').click(function () {
             $.ajax({
                 url: '/Panier/RemoveFromCart',
                 data: { id: $(this).data('id') },
                 type: 'POST',
                 cache: false,
                 success: function (result) {
                     $('#row-' + result.DeleteId).remove();
                     $('#row-' + result.DeleteId).fadeOut('slow');
                     $('#cart-status').text('Cart (' + result.CartCount + ')');
                     $('#update-message').text(result.Message);
                     $('#cart-total').text(result.CartTotal);
                     $.get('@Url.Action("TableContent", "Panier")')
                          $("#TableContent").html(data); });
                  },
                  error: function(XMLHttpRequest, textStatus, errorThrown) { 
                       alert("Status: " + textStatus); alert("Error: " + errorThrown); 
                  }       
             });
             return false;
         });
     });
 </script>
 <h3>
     <em>Details</em> du panier:
 </h3>
 <p class="button">
     @Html.ActionLink("Checkout >>", "AddressAndPayment", "Checkout")
  </p>  
  <div id="update-message">
  </div>
  <div id="table-content">
      @Html.Partial("TableContent")    <=== partial view call
  </div>

PanierController.cs

 using System;
 using System.Collections.Generic;
 using System.Linq;
 using System.Web;
 using System.Web.Mvc;
 using Tp1WebStore3.Models;
 using Tp1WebStore3.ViewModels;

 namespace Tp1WebStore3.Controllers
 {
     public class PanierController : Controller
     {
         //
         // GET: /Panier/
         Tp1WebStoreDBEntities dbProduit = new Tp1WebStoreDBEntities();

         //
         // GET: /ShoppingCart/
         public ActionResult Index()
         {
             var cart = ShoppingCart.GetCart(this.HttpContext);

             // Set up our ViewModel
             var viewModel = new ShoppingCartViewModel
             {
                 CartItems = cart.GetCartItems(),
                 CartTotal = cart.GetTotal()
             };
             // Return the view
             return View(viewModel);
         }
         //
         // GET: /Store/AddToCart/5
         public ActionResult AddToCart(int id)
         {
             // Retrieve the album from the database
             var addedProduit = dbProduit.Produits
                  .Single(produit => produit.ProduitId == id);

             // Add it to the shopping cart
             var cart = ShoppingCart.GetCart(this.HttpContext);

             cart.AddToCart(addedProduit);

             // Go back to the main store page for more shopping
             return RedirectToAction("Index");
         }
         //
         // AJAX: /ShoppingCart/RemoveFromCart/5
         [HttpPost] 
         public ActionResult RemoveFromCart(int id)
         {
             // Remove the item from the cart
             var cart = ShoppingCart.GetCart(this.HttpContext);

             // Get the name of the album to display confirmation
             string produitDescription = dbProduit.Paniers
                 .Single(item => item.PanierId == id).Produit.Description;

             // Remove from cart
             int itemCount = cart.RemoveFromCart(id);

             // Display the confirmation message
             var results = new ShoppingCartRemoveViewModel
             {
                 Message = Server.HtmlEncode(produitDescription) +
                     " has been removed from your shopping cart.",
                 CartTotal = cart.GetTotal(),
                 CartCount = cart.GetCount(),
                 ItemCount = itemCount,
                 DeleteId = id
             };
             return Json(results);  
         /*    return View("CartSummary");  */
         }
         //
         // GET: /ShoppingCart/CartSummary
         [ChildActionOnly]
         public ActionResult CartSummary()
         {
             var cart = ShoppingCart.GetCart(this.HttpContext);

             ViewData["CartCount"] = cart.GetCount();
             return PartialView("CartSummary");
         }

         public ActionResult TableContent()
         {
              return PartialView("TableContent");
         }
     }
 }
user3127986
  • 388
  • 1
  • 10
  • 33
  • You'll probably want to check to see if `cart.GetCartItems()` is not null. related: http://stackoverflow.com/questions/3088147/why-does-net-foreach-loop-throw-nullrefexception-when-collection-is-null – Steven V Mar 13 '14 at 19:26
  • @StevenV I deleted the panier item so it is now empty or null? I just want to refresh the view because currently It is keeping the selected item which I should have been delete. It was deleted from the database but the screen is not refreshing it. I got the message on the screen "your item .... has been deleted." I want the view to not show anymore the item which was deleted. – user3127986 Mar 13 '14 at 19:27

1 Answers1

0

did you make sure Model.CartItems is not null?

try this :

@if (Model.CartItems != null) { <=== add breakpoint here
    foreach (var item in Model.CartItems) <=== error is happening here
    {
        ...
    }
}

and add a breakpoint on the if and check if the value is null ;-)

edited: in the ajax responce, you can reload the partialview ...

success: function (result) {
$('#yourPartialViewContainerId').load('/Action/PartialView');
...

but be sure your foreach items is not null inside your partialView ...

Benoit
  • 1,109
  • 14
  • 29
  • The item has been deleted, The cart should be empty or null not sure. I want the partial view to refresh the screen (just put the header and remove the item from the view on the screen. Right now the database table cart has been deleted but the screen is not being refresh. I got the message "your item .... has been deleted." – user3127986 Mar 13 '14 at 19:35
  • What are we doing if the CartItems is null since I have only 1 item and I remove it ? This is what I am looking for. Thanks – user3127986 Mar 13 '14 at 20:11
  • normaly, you just display items if it's not null, so it load your partianView and the cart is null, so it dont go instde the if(Items != null) and all is fine, no? – Benoit Mar 13 '14 at 20:24
  • I tried it and I got the same error Object reference not set to an instance of an object. at line @if (Model.CartItems != null) I don't get it? – user3127986 Mar 13 '14 at 20:47
  • Maybe the model is null ... or some time the error is not what it seem to be. Try to add a break point and check values to find a null one ... – Benoit Mar 14 '14 at 01:10
  • ru available for a chat ? When I put a break point, The first time I got something in my Cartitems, I deleted the items, when I come back the Model is Null, then PF11 got the error Object reference not set to an instance of an object. Thanks for your help – user3127986 Mar 14 '14 at 12:47