Sergej Popov
Sergej Popov

Reputation: 3021

asp.net page lifecycle issue

I have a user control "header" with label to display amount of item in the basket. it does something like this:

protected void Page_Load(object sender, EventArgs e)
{
    lblBasketCount.Text = Session["basketItemsCount"]!=null?Session["basketItemsCount"].ToString():"0";
}

Then I have a page that has method:

public void btnAddItemToShoppingCart_Click(object sender, EventArgs )
{
    Session["basketItemsCount"] = (from b in db.CartItems where b.crt_ID == cartId select b).Sum(p => p.item_quantity);
}

The problem is that in the page life cycle addItem Method is fired after the control is already had Page_Load event. so my label will refresh only after another reload of the page.
Edit:
Header control is declared in Master Page:

<%@ Register TagPrefix="asp" TagName="Footer" Src="~/Controls/Footer.ascx" %>
    <asp:Header ID="Header" runat="server" />

And Located in Controls folder.

I'm using WAP so its in namespace Sitename.Controls.Header

Upvotes: 1

Views: 353

Answers (3)

Tim Schmelter
Tim Schmelter

Reputation: 460028

Don't use Page_Load event (or other page events) in UserControls. This will lead to issues like this. Instead you should use properties, methods and events in your control.

You could for example have a property BasketCount in your UserControl:

public String BasketCount
{
    get { lblBasketCount.Text; }
    set { lblBasketCount.Text = value; }
}

Then your page can use this property:

var basketCount = (from b in db.CartItems where b.crt_ID == cartId select b).Sum(p => p.item_quantity);
Session["basketItemsCount"] = basketCount;
MyControl.BasketCount = basketCount.ToString();

To get a reference to the control in your MasterPage you should provide a public property there that maps to it:

For example(in MasterPage):

public Header HeaderControl
{
     get
     {
         return Header;
     }
}

And you can call this property from one of your ContentPages in this way(f.e. if your master's type is named "SiteMaster"):

((SiteMaster)Page.Master).HeaderControl.BasketCount = basketCount.ToString();

Upvotes: 1

evasilchenko
evasilchenko

Reputation: 1870

In addition to the earlier answers, another way to accomplish what you want is to use an Update Panel for the control that shows the amount of items in the cart.

http://msdn.microsoft.com/en-us/library/bb399001.aspx

This way you can update it even after the page has loaded.

Upvotes: 1

John Saunders
John Saunders

Reputation: 161773

Don't use Session state for this.

In the user control, add a BasketItemsCount property.

In the Page_Init of the main page, set the property.

In the Page_Load of the user control, use the property to set the label.

Upvotes: 0

Related Questions