Hello, I'm trying to make a simple online journal, and I will get to the part where the user clicks the addtoCart button addtoCart
My model Cart has two properties - Product and quantity
public class Cart { public ProductLanguages Product { get; set; } public int Quantity { get; set; } }
So, in my basketViewModel in my AddProductToCart method AddProductToCart I add a product with the details that I get from the database in a property of type List. Then I save this list in the session. And if, for example, the user clicks the “continue shopping” button and returns to the index page - the next time he clicks “addtocart” for a new product, as you see, I do this check
lstCarts = (List<Cart>)HttpContext.Current.Session["Cart"]; if (lstCarts==null) { lstCarts = new List<Cart>(); }
At first I try to get the list from the session, so I can get previously saved products. But my session is always zero, so I always lose my previously purchased products. Curiously, I'm sure I saved the list of products on this line
HttpContext.Current.Session["Cart"] = lstCarts;
Here is my view model
public class BasketViewModel { private readonly IProductLanguagesRepository prodlanRepository; public List<Cart> lstCarts { get; set; } public BasketViewModel() : this(new ProductLanguagesRepository()) { } public BasketViewModel(IProductLanguagesRepository prodlanRepository) { this.prodlanRepository = prodlanRepository; } public void CreateCart(int id,int quantity) { lstCarts = (List<Cart>)HttpContext.Current.Session["Cart"]; if (lstCarts==null) { lstCarts = new List<Cart>(); } ProductLanguages nwProduct = prodlanRepository.GetProductDetails(id); if (nwProduct != null) { Cart cr = new Cart(); cr.Product = nwProduct; cr.Quantity = quantity; lstCarts.Add(cr); HttpContext.Current.Session["Cart"] = lstCarts; } } }
And my controller
public class BasketManagementController : Controller { public ActionResult Index(int id, int quantity) { BasketViewModel vm = new BasketViewModel(); vm.CreateCart(id, quantity); return View(vm); } }
source share