List C# missing what has already been added

Asked

Viewed 68 times

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;
    }

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>;

He’ll check if the Session already exists, if yes, it fills in the list and will be made a append, case to Session does not exist, a new list is created.

  • 2

    was posting practically the same answer

  • @Leandroangelo this week was helping a friend precisely in this, then when I hit my eye...

  • 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...

  • 1

    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.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.