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
<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
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()
好的,我在这里是基于略读代码的猜测,所以我可能是错的,但是也许第一次不是回发,并且不会调用FillRepeater。
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.