views:

963

answers:

3

Okay, so we all know about changing a master page dynamically in a page's OnPreInit event.

But what about a nested master page? Can I change a master's master?

There is no OnPreInit event exposed in the MasterPage class.

Any ideas?

+4  A: 

Just tested this and it works from the PreInit of the Page that is using the nested MasterPage.

protected void Page_PreInit(object sender, EventArgs e)
{
    this.Master.MasterPageFile = "/Site2.Master";
}

Obviously you will need to ensure that the ContentPlaceholderIds are consistent across the pages you are swapping between.

Andy Rose
Hmm yes that is one solution. Unfortunately that means putting code in every page that uses the Master page rather than in one place.I'm not sure which is the less of two evils... copying the Master Page so there are two copies would be much less work!
Hainesy
+2  A: 

We combine Andy's method with a "BasePage" class - we create a class that inherits from System.Web.UI.Page, and then all our pages inherit from this class.

Then, in our base page class, we can perform the relevant checks to see which root master page should be used - in our case we have a "Presentation" master, and an "Authoring" master - the presentation version has all the navigation and page furniture, along with heavy display CSS, while the authoring master has some extra JS for the authoring tools, lighter CSS, and no navigation (it's what we use when the user is actually authoring a page, rather than modifying the site layout).

This base page can then call Page.Master.MasterPageFile and set it to the Authoring master if that is the correct state for the page.

Zhaph - Ben Duguid
+1  A: 

Just in case anyone stumbles across this and tears their hair out with a "Content controls have to be top-level controls in a content page or a nested master page that references a master page" error when trying Andy's code, get rid of the this.Master. So, the code becomes:

protected void Page_PreInit(object sender, EventArgs e)
{
    MasterPageFile = "/Site2.Master";
}

Edit As Zhaph points out below, the code I have ^^ there will only change the current page's master, not the master's master. This is the code Hainesy was talking about when he mentioned "we all know about changing a master page dynamically" (which I didn't, d'oh). If you happen to get to this page by googling "stackoverflow change master page" (which is what I did) then this is possibly the code you're looking for :-)

Dan F
But that will only change the inner master page, and not the outer one, which is what Hainesy wanted. I'd say you have an issue with with an outer master that doesn't have all the placeholders needed for the inner master.
Zhaph - Ben Duguid
Ahh, gotcha. I had the wrong end of the stick on this one, sorry. I had the stock standard page with one master, rather than a nested master. That'll teach me to read and think first :-)
Dan F
No worries, +1 for your edit :)
Zhaph - Ben Duguid