Dynamically Assigning the Master Page

An entry about asp.net Publication date 3. May 2007 21:29

A while ago, I wrote a post about handling images in themes. At the end of the post I promised to post a way of dynamically assigning the Master Page of any given Page. Well, as it turns out, its actually quite simple - all you have to do is set the MasterPageFile property of the Page during the PreInit stage of the page lifecycle - for example by overriding the OnPreInit method.

Now obviously whichever master page you supply will have to have a set of ContentPlaceHolder controls with ids that match the Content controls on the page - just like you would normally.

This can be a pretty neat way of dynamically loading a master page that for example sits in the current theme directory, essentially allowing you to not only change style information when you switch theme, but also switch the entire master layout. For example, you could do something like:

protected override void OnPreInit(EventArgs e)
{
this.MasterPageFile = String.Format("~/App_Themes/{0}/Theme.Master", this.Theme);
}

Assuming all themes have a Theme.Master file that contains the Master Page definition.

Currently rated 3.0 by 6 people

  • Currently 3/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Powered by BlogEngine.NET 1.4.5.0

Welcome!

My name is Fredrik Kalseth, and this is my blog - thanks for visiting! I am fortunate enough to work with what I love for a living, and this blog is essentially the biproduct of that.

I work as a senior consultant for Capgemini, and am also an active participant in the Norwegian .NET community, as an avid attendee but also as a speaker (most recently at NNUG and MSDN Live).

As a developer, I have a wide circle of interest. My primary passion is for agile, test-driven development, with focus on best practices and clean code. That said, I also love to work on the frontend, especially with web development.

On Twitter? My handle is fkalseth. On LinkedIn? I`m there too.


Disclaimer

This is a personal blog; any opinions expressed here are my own and do not necessarily reflect those of my employer. All content herein is my own original creation, and as such is protected by copyright law. Unless otherwise stated, all source code posted on this blog is freely usable under the Microsoft Permissive License.

What Readers Talk About

Comment RSS