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

≡放荡痞女 提交于 2019-12-22 10:54:30

问题


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

回答1:


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


来源:https://stackoverflow.com/questions/5564359/saving-listcartitem-to-a-session-in-asp-net

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!