我正在尝试将商品添加到购物车中,这些商品会存储在会话中,但是当我将新商品添加到购物车时,会话值会被覆盖。
private List<int> newCart = new List<int>();
protected void dlstCartItems_ItemCommand(object source, DataListCommandEventArgs e)
{
if (e.CommandName == "AddToCart")
{
var arg = e.CommandArgument;
DropDownList ddlList = e.Item.FindControl("ddlAvailableSizes"+e.CommandArgument) as DropDownList;
int currentItemID = int.Parse(this.dlstCartItems.DataKeys[e.Item.ItemIndex].ToString());
if (ddlList.SelectedIndex == 0)
{
ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "alert", "alert('Please Select Size');", true);
}
else
{
newCart.Add(Convert.ToInt32(e.CommandArgument));
Session["Cart"] = newCart;
if (Session["Cart"] != null)
{
int ct = ((List<int>)Session["Cart"]).Count;
lblCartMessage.Text = Convert.ToString(ct)+" "+"Product";
}
}
}
}
我的问题是,当我添加新产品时,旧产品在列表中不再存在,产品数量始终为1.
答案 0 :(得分:2)
您要添加的列表应在类级别定义。无论何时添加新产品,私有List newCart = new List();不应该执行,否则它会在添加后使计数为零,你只剩下最新的添加。
答案 1 :(得分:2)
你在Session["Cart"] = newCart;
覆盖购物车。
为此,写下:
newCart = Session["Cart"] as List<int>;
if (newCart == null)
{
newCart = new List<int>();
Session["Cart"] = newCart;
}
// Rest of the code adding to newCart etc.
答案 2 :(得分:0)
也许newcart在执行dlstCartItems_ItemCommand时总是为空,因此
Session["Cart"] = newCart;
清除值
答案 3 :(得分:0)
protected void dlstCartItems_ItemCommand(object source,DataListCommandEventArgs e) { 列出newCart;
if (e.CommandName == "AddToCart")
{
var arg = e.CommandArgument;
DropDownList ddlList = e.Item.FindControl("ddlAvailableSizes" + e.CommandArgument) as DropDownList;
int currentItemID = int.Parse(this.dlstCartItems.DataKeys[e.Item.ItemIndex].ToString());
if (ddlList.SelectedIndex == 0)
{
ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "alert", "alert('Please Select Size');", true);
}
else
{
if (Session["Cart"] == null)
{
newCart = new List<int>();
newCart.Add(Convert.ToInt32(e.CommandArgument));
Session["Cart"] = newCart;
}
else
{
newCart = Session["Cart"] as List<int>;
newCart.Add(Convert.ToInt32(e.CommandArgument));
Session["Cart"] = newCart;
}
int ct = ((List<int>)Session["Cart"]).Count;
lblCartMessage.Text = Convert.ToString(ct) + " " + "Product";
}
}
}