部分视图错误对象引用未设置不明白为什么

时间:2014-03-13 19:20:23

标签: c# asp.net asp.net-mvc view

我点击“从购物车删除”后出现此错误,“对象”引用未设置为对象的实例。这是在我的部分视图中发生的。有关如何解决此问题的想法吗?

来自Panier的

TableContent.cshtml(部分视图)

 @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>
来自Panier的

Index.cshtml

 @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");
         }
     }
 }

1 个答案:

答案 0 :(得分:0)

你确定Model.CartItems不是null吗?

试试这个:

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

并在if上添加断点并检查该值是否为null; - )

编辑: 在ajax响应中,你可以重新加载partialview ...

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

但请确保您的partialView项目中的foreach项目不为空...