将列表<cartitem>保存到ASP.NET中的会话</cartitem>

时间:2011-04-06 09:42:52

标签: c# asp.net sql session httpcontext

CartItems保存在SQL数据库中。

我想将所有CartItem放入List并转移到Instance.Items。

实例变量正在保存到会话中。

代码如下。

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

返回List的代码。我想将从此函数返回的List保存到Instance.Items。这样它就可以保存到会话中。

    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 个答案:

答案 0 :(得分:1)

如果您要将整个对象提交到会话,则应将这些项目存储在与该对象的会话中。

为什么不做这样的事呢?:

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