У меня проблема с созданием корзины покупок. Я создал весь механизм, который поддерживает добавление, однако, когда я пытаюсь прочитать модель с продуктами, я получаю сообщение об ошибке: System.NullReferenceException: «Ссылка на объект не установлена для экземпляра объекта». System.Web. Mvc .WebViewPage .Model.get вернул null.
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");
}
}
}
CartMenager.cs
namespace SynergieBooksShop.Infrastructure
{
public class CartMenager
{
private ProductRepo _productRepo;
private OrderRepo _orderRepo;
private CartPositionRepo _cartRepo;
private ISessionMenager session;
public CartMenager(ISessionMenager session, ProductRepo _productRepo, OrderRepo _orderRepo, CartPositionRepo _cartRepo)
{
this.session = session;
this._productRepo = _productRepo;
this._orderRepo = _orderRepo;
this._cartRepo = _cartRepo;
}
public List<CartPosition> TakeCart()
{
List<CartPosition> cart;
if (session.Get<List<CartPosition>>(Consts.CartSessionKey)==null)
{
cart = new List<CartPosition>();
}
else
{
cart = session.Get<List<CartPosition>>(Consts.CartSessionKey) as List<CartPosition>;
}
return cart;
}
public void AddToCart(int productId)
{
var cart = TakeCart();
var cartPosition = cart.Find(k => k.Product.ProductId == productId);
//var cartPositio1 = _cartRepo.GetOne(productId);
if (cartPosition != null)
cartPosition.Quantity++;
else
{
var productToAdd = _productRepo.GetAll().Where(p => p.ProductId == productId).SingleOrDefault();
if (productToAdd != null)
{
var newCartPosition = new CartPosition()
{
Product = productToAdd,
Quantity = 1,
Value = productToAdd.ProductPrice
};
cart.Add(newCartPosition);
}
}
session.Set(Consts.CartSessionKey, cart);
}
...
Помещая точки останова, я вижу, что CartController создает объект CartViewModel cartVM с другими объектами, так почему представление видит его как ноль? Спасибо за помощь:)