So far I made my site responsive without postback when adding products to cart( adds Product.Id
to a cookie with JQuery).
When user visit the Cart/Checkout page, I read all Id
's from cookie in Controllers and put all records into a cartList
and pass it to the View.
Now I'm stuck as I don't know how to solve it without postback when I want to remove a product from the cart.
Is it possible to do something similar/corresponding like:
cartList.Remove(db.Products.SingleOrDefault(x=> x.Id == /*Id to remove from cart*/));
in View?
My code:
I added Product.Id
into cookie with JQuery (gets id data-id="@item.ID"
from foreach loop):
$('.add-to-cart').click(function () {
if ($.cookie("AddedProductId") != null) {
var previousValues = $.cookie("AddedProductId");
$.cookie("AddedProductId", previousValues + '_' + $(this).data('id'));
}else{
$.cookie("AddedProductId", $(this).data('id'));
}
});
This is how I maintain cartList
with added products, inside Controller when you visit cart/checkout page:
public ActionResult Cart(){
var cart = Request.Cookies["AddedProductId"].Value;
String[] elements = Regex.Split(cart, "_");
List<Product> cartList = new List<Product>();
foreach (var item in elements){
cartList.Add(db.Products.SingleOrDefault(x => x.ID == new Guid(item)));
}
return View(cartList);
}
I then display everything with a foreach
loop inside /Cart/View
.
What's the best option to solve this for Asp.Net MVC?