储蓄List< CartItem>到ASP.NET中的会话
本文关键字:NET 会话 ASP List CartItem 储蓄 | 更新日期: 2023-09-27 17:49:27
CartItems保存在SQL数据库中。
我想把所有的CartItems放到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;
}
如果要将整个对象提交到session,则条目应该与对象一起存储在session中。
为什么不这样做呢?:
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;
}
}