How to Set Master Page dynamically?

During the PreInit stage of page processing in ASP.NET, it is possible to dynamically assign a master page to a content page. This is because the merging of the master page and content page occurs during the initialization stage of page processing, and therefore, a master page needs to be assigned before this stage.

PreInit stage

Assigning a master page dynamically during the PreInit stage, you have the flexibility to determine the master page at runtime based on certain conditions or user preferences. This allows for a more dynamic and adaptable approach to page layout and functionality.

It is important to note that the master page assignment should be done early in the page lifecycle, specifically during the PreInit stage, to ensure that the master page is properly applied and that any controls or elements defined in the master page are available to the content page during subsequent stages of page processing.

void Page_PreInit(Object sender, EventArgs e) { this.MasterPageFile = "~/NewMaster.master"; }

PreInit event

The PreInit event in ASP.NET provides a valuable opportunity to examine and validate various conditions and properties of the page request. This includes checking if the page is being loaded in response to a postback and accessing the values of profile properties. It is important to note that once the PreInit event is completed, any attempt to modify the MasterPageFile property will result in an InvalidOperationException exception being thrown.

By utilizing the PreInit event, you can perform necessary checks and validations before the page is fully initialized. This allows you to make informed decisions and take appropriate actions based on the specific requirements of the page. However, it's crucial to be aware that setting an invalid value for the MasterPageFile property during the PreInit event will not immediately throw an exception. Instead, an exception of type HttpException will be thrown later in the page life cycle if the MasterPageFile property remains invalid.

Conclusion

Using the ability to assign a master page dynamically during the PreInit stage, you can tailor the appearance and behavior of your web pages based on specific requirements or user preferences, providing a more personalized and interactive experience for your users.