我在创建购物车时遇到问题。我已经创建了支持添加的整个机制,但是当我尝试使用产品读取模型时,出现错误: System.NullReferenceException:“对象引用未设置为对象的实例。” System.Web.Mvc.WebViewPage .Model.get返回null。
1. [1, 1, 1, 1, 1, 0, 0]
2. [1, 1, 1, 1, 0, 1, 0]
3. [1, 1, 1, 1, 0, 0, 1]
4. [1, 1, 1, 0, 1, 1, 0]
5. [1, 1, 1, 0, 1, 0, 1]
6. [1, 1, 1, 0, 0, 1, 1]
7. [1, 1, 0, 1, 1, 1, 0]
8. [1, 1, 0, 1, 1, 0, 1]
9. [1, 1, 0, 1, 0, 1, 1]
10. [1, 1, 0, 0, 1, 1, 1]
11. [1, 0, 1, 1, 1, 1, 0]
12. [1, 0, 1, 1, 1, 0, 1]
13. [1, 0, 1, 1, 0, 1, 1]
14. [1, 0, 1, 0, 1, 1, 1]
15. [1, 0, 0, 1, 1, 1, 1]
16. [0, 1, 1, 1, 1, 1, 0]
17. [0, 1, 1, 1, 1, 0, 1]
18. [0, 1, 1, 1, 0, 1, 1]
19. [0, 1, 1, 0, 1, 1, 1]
20. [0, 1, 0, 1, 1, 1, 1]
21. [0, 0, 1, 1, 1, 1, 1]
index.cshtml
@model SynergieBooksShop.ViewModels.CartViewModel
@using SynergieBooksShop.Infrastructure
@{
ViewBag.Title = "Cart";
}
<h2>Index</h2>
@foreach (var cartPosition in Model.CartPositions) <---- Here is error
{
@cartPosition.Product.ProductTitle <br>
@cartPosition.Quantity <br>
@cartPosition.Value
}
<div id="cart-empty-message" @if (Model.CartPositions != null && Model.CartPositions.Count > 0) { <text>class="hidden"</text>}>
<p>Your cart is empty</p>
</div>
</hr>
Total Price: <span id="total-price">@Model.TotalPrice</span> pln
CartViewModel.cs
namespace SynergieBooksShop.ViewModels
{
public class CartViewModel
{
public List<CartPosition> CartPositions { get; set; }
public decimal TotalPrice { get; set; }
}
}
CartController.cs
namespace SynergieBooksShop.Controllers
{
public class CartController : Controller
{
private CartMenager cartMenager;
private ISessionMenager sessionMenager { get; set; }
private ProductRepo _productRepo;
private OrderRepo _orderRepo;
private CartPositionRepo _cartRepo;
public CartController(){
_productRepo = new ProductRepo();
_orderRepo = new OrderRepo();
_cartRepo = new CartPositionRepo();
sessionMenager = new SessionMenager();
cartMenager = new CartMenager(sessionMenager, _productRepo, _orderRepo, _cartRepo);
}
// GET: Cart
public ActionResult Index()
{
var cartPositions = cartMenager.TakeCart();
var totalPrice = cartMenager.TakeCartValue();
CartViewModel cartVM = new CartViewModel()
{
CartPositions = cartPositions,
TotalPrice = totalPrice
};
return View();
}
public ActionResult AddToCart(int id)
{
cartMenager.AddToCart(id);
return RedirectToAction("Index");
}
}
}
通过放置断点,我看到CartController与其他对象一起创建了CartViewModel cartVM对象,为什么视图将其视为null? 感谢您的帮助:)
答案 0 :(得分:0)
您没有将数据返回到视图。 应该是:
return View(cartVM);