views:

70

answers:

2

I am trying to change the master page dynamically, and although it's easy to do from a content page (overriding OnPreInit), there is no such event for a master page. Is it possible to introduce this event somehow?

UPDATE: I got halfway there by going via the PreInit of the pages at the bottom of the ladder, turns out you can do things like base.Master.MasterPageFile = "/master.Master";, but for some reason this doesn't load the stuff in the header of the top-most master page, namely stylesheets.

A: 

If you overrode the MasterPageClass and added your own onPreInit you might could do it, but I don't think even that would work. There's definitely no construct for it according to Reflector, nothing to even override, altho since it inherits UserControl then there's always OnInit ... alternately you could attempt to override get_Master() but that might not work either ...

drachenstern
Yeah that's the thing, there is no event to override. OnInit() occurs too late in the lifecycle, so that's no use. What's get_Master()?
Shagglez
it's an internal method being called by the page but if you use RedGate Reflector then you'll see it ... I strongly suggest you to start using Reflector if you're not already, it will help explain a lot about the .NET code you're using...
drachenstern
A: 

Quoting from: http://stackoverflow.com/questions/581950/can-i-change-a-nested-master-pages-master-dynamically

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.

Kamyar
Hehe, funny, I found this out myself by trial and error, but as I've mentioned this doesn't quite solve the problem. The master page file is loaded, however the style sheets that are in the header are not.
Shagglez
Is your master page in a different folder than the content pages?
Kamyar
If so, your problem is related to not resolving paths correctly at runtime in your master page. some workarounds are mentioned at: http://forums.asp.net/t/1401917.aspx
Kamyar
Hmm, I had a look at the forum post, and at least on the first glance, it seems that they are using relative paths, which is where the problem arising. I always try to use paths like "/assets/site/css..." etc, so that no matter which page links the css, path resolves correctly. I think for the moment I will hardwire some css, and try to get a solution at a later point
Shagglez
Actually this solution is the correct one. I completely forgot about the bog standard reset at the beginning of css, which was clearing all the styles. You can have the correct answer, although I updated my post before that. Also I think the other answer deserves a point :)
Shagglez