1
I’m a beginner and I’m developing a shopping cart. The routine I thought was: Every time I click the add button, the product is sent to the controller via ajax request. I already have a list created there. So, I add the product to the list and save the list in a Session. Return to Session for view and populate my shopping cart. But this caused me a problem, with each click, the method is called and consequently the list is instantiated again, this gives a clear in my list and lose the products added earlier. The purpose of this is to allow the user to navigate between pages without losing what is added in the cart.
public JsonResult AddCart(int _cod, string _foto, string _nome, string _categoria, decimal _desconto, decimal _preco)
{
List<Produtos> listCart = new List<Produtos>();
Produtos item = new Produtos();
item.cod = _cod;
item.foto = _foto;
item.nome = _nome;
item.categoria = _categoria;
item.desconto = _desconto;
item.preco = _preco;
listCart.Add(item);
Session["SessionList"] = listCart;
var list = Session["SessionList"] as List<Produtos>;
var v = Json(new { listCart }, JsonRequestBehavior.AllowGet);
return v;
}
was posting practically the same answer
– Leandro Angelo
@Leandroangelo this week was helping a friend precisely in this, then when I hit my eye...
– Barbetta
Very good! It worked, thanks! Just to enjoy the post, this is the best way to do it? I was reading an article that says Session consumes too much server resource...
– Gabriel Belgamo
Not only is it a question of consuming resources, but the ideal is to keep your solution as stateless as you can. For example if you have a Web.API layer the two applications will not share the same session.
– Leandro Angelo