Tuesday, 20 March 2012

How to set master page file at run time

When you are developing a web site using Master and Content page model, you have noticed that after creating your Master page in the web application when you use Wizard to add Content page, it asks you to pick the master page that you would like to associate with this page. And if you choose the option of not selecting a master page, then wizard gives you a standard web form. Then you will have to manually delete markup for body, header etc. to convet it to a content page.
If you do pick the option of selecting a master page, then your content page's declaration at the top looks like the following snippet.

<%@ Page Title="" Language="C#" 
MasterPageFile="~/Themes/Default/ByteBlocks.master" 
AutoEventWireup="true" 
CodeFile="Default.aspx.cs" 
Inherits="_Default" %>

Notice use of MasterPageFile attribute that specifies what master page this content page is associated with. What if you want to switch your master page at run time based on some configuration settings or some use choice. Does this mean you will have to find a way to modify your ASPX file to do. No there is a easier solution to it.
For example in my project I added a drop down in master page to change the theme on the fly. And then PreInit event handler of the page, I set MasterPageFile property of the page object. This is the same attribute that was set at top of the page when we added content page using wizard.

protected override void OnPreInit(EventArgs e)
{
if (Session["theme"] != null)
{
MasterPageFile = 
string.Format("~/Themes/{0}/ByteBlocks.master", Session["theme"]);
}
base.OnPreInit(e);
}

It is very important that you set MasterPageFile property in or before PreInit step of life of ASPX page. Otherwise applicaiton will throw run time exception.
System.InvalidOperationException: The 'MasterPageFile' property can only be set in or before the 'Page_PreInit' event.

No comments:

Post a Comment