3
CartItems保存在SQL數據庫中。將保存列表<CartItem>添加到ASP.NET中的會話中
我想把所有的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;
}
對,所以什麼是你遇到的問題? – ilivewithian 2011-04-06 09:44:30
如果你的代碼和發佈完全一樣,你的靜態構造函數調用它自己(Instance = new ShoppingCart();) – RichardW1001 2011-04-06 09:56:30
Oh和BTW這一行 - String sql =「Select * from Cart where CustomerId ='」+ CustomerId +''「; - 正在詢問SQL注入攻擊 – RichardW1001 2011-04-06 09:58:44