Mvc - save the list in the session and then get its value

Hello, I'm trying to make a simple online journal, and I ended up in the part where the user clicks the addtoCart button

My Cart model has two properties - product and quantity.

public class Cart { public ProductLanguages Product { get; set; } public int Quantity { get; set; } } 

So, in my ViewModel basket (class) inside my AddProductToCart method, I add a product whose data I get from the database in the List property.

Therefore, I cannot understand this problem: somewhere in the control I have to save this list in the session, and if the user adds more products, next time I will get the list from this session. If someone can give me an example of a controller with an index action that can do this, I would be very grateful.

 public class BasketViewModel { private readonly IProductLanguagesRepository prodlanRepository; public List<Cart> listProductsinBasket { get; set; } public BasketViewModel() : this(new ProductLanguagesRepository()) { } public BasketViewModel(IProductLanguagesRepository prodlanRepository) { this.prodlanRepository = prodlanRepository; } public void AddProductToCart(int id,int quantity) { ProductLanguages nwProduct = prodlanRepository.GetProductDetails(id); if (nwProduct != null) { Cart cr = new Cart(); cr.Product = nwProduct; cr.Quantity = quantity; listProductsinBasket.Add(cr); } 
+6
source share
1 answer

Store:

 HttpContext.Session["list"] = new List<object> { new object(), new object() }; 

Download:

 var list = HttpContext.Current.Session["list"] as List<object>; 
+4
source

All Articles