title: Cart Session for Logged in Users .Net MVC
body: <p>I am stuck on Cart Sessions when User is logged in. Here is the situation. </p>
  
  <p>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.</p>
  
  <p>This is the Action for Cart Controller</p>
  
  <pre><code>public ActionResult Buy(int id)
  {
      ProductModel productModel = new ProductModel();
      if (Session["cart"] == null)
      {
          List&lt;Item&gt; cart = new List&lt;Item&gt;();
          cart.Add(new Item { Product = productModel.find(id), Quantity = 1 });
          Session["cart"] = cart;
      }
      else
      {
          List&lt;Item&gt; cart = (List&lt;Item&gt;)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&lt;Item&gt; cart = (List&lt;Item&gt;)Session["cart"];
      int index = isExist(id);
      cart.RemoveAt(index);
      Session["cart"] = cart;
      return RedirectToAction("Index");
  }
  
  private int isExist(int id)
  {
      List&lt;Item&gt; cart = (List&lt;Item&gt;)Session["cart"];
      for (int i = 0; i &lt; cart.Count; i++)
          if (cart[i].Product.Id.Equals(id))
              return i;
      return -1;
  }
  </code></pre>
  
  <p>This is Product Model</p>
  
  <pre><code>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; }
  }
  </code></pre>
  
  <p>This is Item Model</p>
  
  <pre><code>public class Item
  {
      public Product Product
      {
          get;
          set;
      }
  
      public int Quantity
      {
          get;
          set;
  
      }
  }
  </code></pre>
  
  <p>This is User Model</p>
  
  <pre><code>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; }
  }
  </code></pre>
  
  <p>Please help with this </p>