Search code examples
c#asp.netsqlsessionhttpcontext

Saving List<CartItem> to a Session in ASP.NET


CartItems are saved in the the SQL database.

I want to put all CartItems in a List and transfer to Instance.Items.

The Instance Variable is being saved into the session.

The code is below.

public class ShoppingCart
{
    public List<CartItem> Items { get; private set; }
    public static SqlConnection conn = new SqlConnection(connStr.connString);
    public static readonly ShoppingCart Instance;

    static ShoppingCart()
    {
        if (HttpContext.Current.Session["ASPNETShoppingCart"] == null)
        {
                Instance = new ShoppingCart();
                Instance.Items = new List<CartItem>();
                HttpContext.Current.Session["ASPNETShoppingCart"] = Instance;  
        }
        else
        {
            Instance = (ShoppingCart)HttpContext.Current.Session["ASPNETShoppingCart"];
        }
    }

The code that returns List . I want to save the List that is being returned from this function to Instance.Items. So that it can be saved into the session.

    public static List<CartItem> loadCart(String CustomerId)
    {
        String sql = "Select * from Cart where CustomerId='" + CustomerId + "'";
        SqlCommand cmd = new SqlCommand(sql, conn);
        List<CartItem> lstCart = new List<CartItem>();
        try
        {
            conn.Open();
            SqlDataReader reader = cmd.ExecuteReader();
            while (reader.Read())
            {
                CartItem itm = new CartItem(Convert.ToInt32(reader["ProductId"].ToString()));
                itm.Quantity = Convert.ToInt32(reader["Quantity"].ToString());
                lstCart.Add(itm);
            }

        }
        catch (Exception ex)
        { }
        finally
        {
            conn.Close();
        }

        return lstCart;
    }

Solution

  • If you're committing the entire object to session, the items should be stored in session with the object.

    Why not do something like this instead?:

    public class ShoppingCart
    {
        public List<CartItem> Items { get; private set; }
        public static SqlConnection conn = new SqlConnection(connStr.connString);
        public static readonly ShoppingCart Instance;
    
        static ShoppingCart RetrieveShoppingCart()
        {
            if (HttpContext.Current.Session["ASPNETShoppingCart"] == null)
            {
                    Instance = new ShoppingCart();
                    Instance.Items = new List<CartItem>();
                    HttpContext.Current.Session["ASPNETShoppingCart"] = Instance;  
            }
            else
            {
                Instance = (ShoppingCart)HttpContext.Current.Session["ASPNETShoppingCart"];
            }
    
            return Instance;
        }
    }