List C # losing what has already been added

1

I'm a beginner and I'm developing a shopping cart. The routine I thought was: Every click on the add button, the product is sent to the controller via ajax request. There I already have a list created. So, I add the product in 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 I lose the products added previously. The purpose of this is to allow the user to navigate between pages without losing what they are adding to 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;
    }
    
asked by anonymous 07.05.2018 / 20:13

1 answer

3

This is because you are not assigning to the list what is already saved.

At the beginning of your method add the following code

List<Produtos> listCart;
if(Session["SessionList"] == null)
     listCart = new List<Produtos>();
else
    listCart = Session["SessionList"] as List<Produtos>;

It will check if Session already exists, if so, it fills the list and will be done append , if Session does not exist, a new list is created.

    
07.05.2018 / 20:21