Setting the MasterPageFile Property Using Code

In this lesson, you will learn the difference between setting the MasterPageFile property in code and in design-time.

We'll cover the following

MasterPageFile attribute

Setting the MasterPageFile attribute in the @Page directive has the net effect of assigning the page’s MasterPageFile property during the initialization stage. This is the very first stage of the page’s life-cycle. This property can be set programmatically. This property is set before the fusion takes place.

PreInit stage

At the start of the PreInit stage, the page object raises its PreInit event, and the OnPreInit method is called. Then the event handler for the Init event is called or the OnPreInit method is overridden.

During the initialization stage, the page object’s MasterPageFile property is assigned the value of the MasterPageFile attribute in the @Page directive. This is followed by the PreInit stage. Here, the page object’s MasterPageFile property is set and overrides the @Page directive.

Whether the MasterPageFile property is set via the @Page directive or in a programmatic way is not important for the end-user. But Visual Studio uses the @Page directive during the design time to get a view of the design. If you return to Default.aspx in the design you get an error. An example of this error is given below.

So, you need to leave the MasterPageFile attribute in the @Page directive to enjoy a rich design-time experience in Visual Studio.