Runtime Master Pages
January 23rd, 2009Master pages are great time savers in ASP.NET and we use them extensively to simplify user interface management in our applications. Recently, I ran into a situation where the master page to be used needed to be set from the Database. Turns out this is relatively simple to do if you know the path to the master page. You need to harness the Page_PreInit event that fires before the Page_Load and set the master page at runtime:
protected void Page_PreInit (object sender, EventArgs e) {
this.MasterPageFile = "~/path/to/masterpage.master";
}
The other problem I ran into was accessing a control on the master page from the web form that uses the master as a template. This is important because if all the inter-changeable master pages have the same control names they become useable from the web form irrespective of their location on the page. One way is to define the same content areas in all the master pages and set them accordingly within the child, however in many cases you’d be duplicating the code relating to the control on the web forms. The other option is to use the FindControl function on the Master object. In order for this to work it needs to be cast to the appropriate control class. In the case of a Literal the syntax works out like this:
((Literal)this.Master.FindControl("literalControl")).Text = "Foobar";
Nice and easy.
