1

我正在尝试将项目添加到存储在会话中的购物车,但是当我将新产品添加到购物车时会话值被覆盖。

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。

4

4 回答 4

2

您要添加的列表应在类级别定义。每当您添加新产品时,私有列表 newCart = new List(); 不应该执行,否则它会使添加后计数为零,您只会留下最新的添加。

于 2012-07-30T09:21:29.823 回答
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.
于 2012-07-30T09:21:48.250 回答
0

也许 newcart 在执行 dlstCartItems_ItemCommand 时总是为空,因此

Session["Cart"] = newCart; 

清除值

于 2012-07-30T09:21:47.463 回答
-1

protected void dlstCartItems_ItemCommand(object source, DataListCommandEventArgs e) { List 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";




        }



    }
}
于 2012-07-30T11:10:04.343 回答