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
Don’t use
Page_Loadevent (or other page events) inUserControls. 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
BasketCountin your UserControl:Then your page can use this property:
To get a reference to the control in your
MasterPageyou should provide a public property there that maps to it:For example(in MasterPage):
And you can call this property from one of your ContentPages in this way(f.e. if your master’s type is named “SiteMaster“):