Content page controls cleared after updating Master page controls

It seems like accessing a Master page’s controls before they have loaded will clear out the ContentPlaceHolders thereby not show content specified in a content page.

This is my scenario. I put a public property (bodycssclass) on my content page which I set in the following way:

<%@ Page MasterPageFile="MyMaster.master" bodycssclass="home" ... %>
    public class PageBase : System.Web.UI.Page
    {
        public string BodyCssClass
        {
            get;
            set
            {
                MasterPageBase mpbCurrent = this.Master as MasterPageBase;
                mpbCurrent.BodyCssClass = BodyCssClass;
            }
        }
    }

This public property then sets a public property on the master page.  The public property on the master page modifies some of it controls, it seems like this causes a problem. The content page simply shows blank areas where content has been defined in asp:Content tags. I think it may something to do with accessing Master page controls before the Master page OnLoad event has fired. For reference here is the order of page events:

Page.OnPreInit()
UserControl.OnInit()
MasterPage.OnInit()
Page.OnInit()
Page.OnInitComplete()
Page.OnLoad()
MasterPage.OnLoad() (I must have been setting my property before this step)
UserControl.OnLoad()
Page.OnLoadComplete()
Page.OnPreRender()
MasterPage.OnPreRender()
UserControl.OnPreRender()
Page.OnPreRenderComplete()
Page.OnSaveStateComplete()
UserControl.OnUnload()
MasterPage.OnUnload()
Page.OnUnload()

Solution

The Content page inherits from a common base page which saves the value defined and processes it later like so:

    public class PageBase : System.Web.UI.Page
    {
        public string BodyCssClass
        {
            get;
            set;
        }

        protected override void OnLoadComplete(EventArgs e)
        {
            MasterPageBase mpbCurrent = this.Master as MasterPageBase;
            mpbCurrent.BodyCssClass = BodyCssClass;

            base.OnLoadComplete(e);
        }
    }
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s