Shopping Cart Doesn’t Let You Add More Items After Cleaning It

Asked

Viewed 41 times

0

I’m making a shopping cart for an E-commerce test on ASP.NET MVC, working with EF6. I was doing the logic, the cart it adds products and also removes. However, every time I add several products, and then remove them all, it doesn’t let me add any more. The problem seems to be in the object Session["carrinho"] that does not return null when all items have been removed. Follow the methods responsible for managing the cart:

Add Method:

public ActionResult Compra(int id)
    {
        if(Session["carrinho"] == null)
        {
            List<Item> carrinho = new List<Item>();
            var produtos = db.produto.Find(id);
            carrinho.Add(new Item()
            {
                produto = produtos,
                Quantidade = 1
            });
            Session["carrinho"] = carrinho;
        }
        else
        {
            List<Item> carrinho = (List<Item>)Session["carrinho"];
            var produtos = db.produto.Find(id);
            foreach(var item in carrinho)
            {
                if(item.produto.CodBarra == id)
                {
                    int qtd = item.Quantidade;
                    carrinho.Remove(item);
                    carrinho.Add(new Item()
                    {
                        produto = produtos,
                        Quantidade = qtd+1
                    });
                    break;
                }
                else
                {
                    carrinho.Add(new Item()
                    {
                        produto = produtos,
                        Quantidade = 1
                    });
                    break;
                }
            }
            Session["carrinho"] = carrinho;
        }
        return RedirectToAction("Index");
    }

Remove Method:

public ActionResult RemoverProd(int id)
    {
        List<Item> carrinho = (List<Item>)Session["carrinho"];
        var produtos = db.produto.Find(id);
        foreach (var item in carrinho)
        {
            if(item.produto.CodBarra == id)
            {
                carrinho.Remove(item);
                break;
            }
        }
        Session["carrinho"] = carrinho;
        return RedirectToAction("Index");
    }

I would like to receive help to solve this problem

  • 1

    I won’t get too into the merits of your code but if you want to have an empty list you could just put a new condition in your if besides checking only for null, for example: if(Session["cart"] == null || ! ((List<Item>)Session["cart"]). Any())

  • It worked perfectly, now I can add items even zeroing the cart.

No answers

Browser other questions tagged

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