保存列表到 ASP.NET 中的会话
购物车项目保存在 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 的代码。我想将从该函数返回的列表保存到 Instance.Items。这样就可以保存到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;
}
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;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(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?: