MasterPages in .NET v1.* -- Dynamic Masters
It seems that lately my implementation of MasterPages for .NET v1.* is getting a lot of hits again, which is kind of funny considering its been out for over a year. Anyhow, one of the questions that I get asked a lot is how to dynamically change the master template at runtime, which is obviously possible since I do it on my own site. The solution to this problem all comes down to timing -- the Init event is already too late, so you need something earlier, like the AddParsedSubObject override. Just be aware that this method is called for every root object added to the page, so make sure that you wrap any code you add to this method so that it only gets ran once. So here's the code:
protected override void AddParsedSubObject(object obj) {
base.AddParsedSubObject(obj);
if (obj is MasterPage) {
((MasterPage) obj).TemplateFile = "~/Template.ascx";
}
}
Note that while you can add this code to each page, MasterPages doesn't preclude you from using a base page class -- I put this code in my base page class on my site. Also note that you can use any of the Request collections (Form, QueryString, Cookies), or Session, as the basis of your choice for the TemplateFile to make it truly dynamic. Finally, if you are already playing with .NET v2.0, then see my Whidbey article for a version of this code that uses the TestDeviceFilter override, although this may change as Whidbey matures. Note that my Whidbey article also has a fully functioning version of everything in the article for the .NET v1.* scenario in the download -- so its not just about Whidbey.