Cart Session for Logged in Users .Net MVC

Viewed 547

I am stuck on Cart Sessions when User is logged in. Here is the situation.

User logs in and adds product to cart, but when Logs Out the Cart is empty. How can we ensure the Cart Session for that specific user stays even after user logs out keeping items in cart.

This is the Action for Cart Controller

public ActionResult Buy(int id)
{
    ProductModel productModel = new ProductModel();
    if (Session["cart"] == null)
    {
        List<Item> cart = new List<Item>();
        cart.Add(new Item { Product = productModel.find(id), Quantity = 1 });
        Session["cart"] = cart;
    }
    else
    {
        List<Item> cart = (List<Item>)Session["cart"];
        int index = isExist(id);
        if (index != -1)
        {
            cart[index].Quantity++;
        }
        else
        {
            cart.Add(new Item { Product = productModel.find(id), Quantity = 1 });
        }
        Session["cart"] = cart;
    }
    return RedirectToAction("Index");
}

public ActionResult Remove(int id)
{
    List<Item> cart = (List<Item>)Session["cart"];
    int index = isExist(id);
    cart.RemoveAt(index);
    Session["cart"] = cart;
    return RedirectToAction("Index");
}

private int isExist(int id)
{
    List<Item> cart = (List<Item>)Session["cart"];
    for (int i = 0; i < cart.Count; i++)
        if (cart[i].Product.Id.Equals(id))
            return i;
    return -1;
}

This is Product Model

public class Product
{
    [Key]

    public int Id { get; set; }

    public string Name { get; set; }

    public double Price { get; set; }

    public string Photo { get; set; }

    public string Desc { get; set; }
}

This is Item Model

public class Item
{
    public Product Product
    {
        get;
        set;
    }

    public int Quantity
    {
        get;
        set;

    }
}

This is User Model

public class User
{
    [Key]
    public int Id { get; set; }
    public string FullName { get; set; }
    public string UserName { get; set; }
    public string Password { get; set; }
    public string AccountType { get; set; }
}

Please help with this

1 Answers

The cart is empty after logout because the session is deleted. If you want to persist the cart-items you should store them somewhere.

Possible solutions:

  1. Use localstorage on the client to store the id's of the added items
  2. Store them in a database and add them to the cart on login
Related