简体   繁体   English

购物车问题,asp.net C#

[英]Problem with shopping cart, asp.net c#

I have built a simple shopping cart. 我已经建立了一个简单的购物车。 The problem is that the first time i try to add an item nothing happens. 问题是我第一次尝试添加项目时没有任何反应。 If i click the buy button a second time an item is added. 如果我第二次单击购买按钮,则会添加一个项目。 What is the cause if this problem? 如果出现此问题是什么原因?

Thanx! 感谢名单!

.aspx 的.aspx

<asp:Content ContentPlaceHolderID="main" runat="server">
White lily
<asp:Button ID="button" runat="server" OnClick="buy_Click" />
</asp:Content>

<asp:Content ContentPlaceHolderID="rightBar" runat="server">
    <UserControl:ShoppingCart id="shoppingCart" runat="server" />
</asp:Content>

.ascx 的.ascx

public partial class UserControls_ShoppingCart : System.Web.UI.UserControl
{
    private List<Flower> FlowerList 
    {
        get
        {
            List<Flower> tmp = Session["FlowerList"] as List<Flower>;
            if (tmp == null)
            {
                tmp = new List<Flower>();
            }
            return tmp;
        }
    }

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
            FillRepeater();
        }

    }

    public void ShoppingCart_ItemDataBound(object sender, RepeaterItemEventArgs e)
    {
        if (e.Item != null)
        {
            Label itemLabel = e.Item.FindControl("itemLabel") as Label;
            Flower flower = e.Item.DataItem as Flower;
            if (flower != null)
            {
                itemLabel.Text = flower.getName(flower);
            }
        }
    }

    private void FillRepeater()
    {
        shoppingCartRepeater.DataSource = FlowerList;
        shoppingCartRepeater.DataBind();
    }

    public void AddFlower(Flower flower)
    {
        FlowerList.Add(flower);
        Session["FlowerList"] = FlowerList;
        FillRepeater();
    }
}

Pursuant to my comment on the first answer.. try this 根据我对第一个答案的评论。

 private List<Flower> FlowerList 
    {
        get
        {
             return(_FlowerList);
        }
        set
        {
            _FlowerList = value;
        }

    }
    protected List<Flower> _FlowerList = new FlowerList();
    protected void Page_Load(object sender, EventArgs e)
    {
       if (Session["FlowerList"]!= null) {
           FlowerList = (List<Flower>)Session["FlowerList"];
       }
        if (!Page.IsPostBack)
        {
            FillRepeater();
        }
    }

It should work with everything else the same. 它应该与其他所有东西都一样。 A better way would be to use ViewState though, and save the value of _FlowerList in SaveViewState() 更好的方法是使用ViewState,然后将_FlowerList的值保存在SaveViewState()中

好的,我在这里是基于略读代码的猜测,所以我可能是错的,但是也许第一次不是回发,并且不会调用FillRepeater。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM