views:

25

answers:

3

Hi, I am working with a third party asp.net application that uses master pages and nested master pages. My needs are to dynamically set the master page files for each page(.aspx). The application by default sets the master page file in the strongly typed @Page directive for each page. I don't want to change the strongly typed directive on each page (over 50 pages) because I am lazy and I want to minimize conflicts with future upgrades.

My solution was to use the base masterpage class and override the OnPreInt event like this:

protected override void OnPreInit(EventArgs e)
    {
    this.MasterPageFile = "~/MasterPages/MyMaster.master";
    }

Everything works perfectly. My question is: Is this a bad idea and why? It just seems too easy to be true.

thanks.

A: 

It makes code / logic more complicated. Other guys who may continue working on the project after you for example may have problems with understand it quickly. IMHO

Koistya Navin
That makes sense. Ideally I would like to remove the strongly typed portion all together but I don't control that. This is mainly to make themeing easier.
Joe, I don't see any problems with your approach other than ease of readability. You can also try dig into native ASP.NET theming, but it is possible that your approach will be more simple.
Koistya Navin
Without going to far off topic I just find it cumbersome to try and 'fit' a custom theme and layout into someone else's markup(masterpage). I wanted the freedom to design a layout/theme using my own classes/id's/etc and change it when needed. Thanks for the input Koistya.
A: 

This should work without issue. The MasterPage is not applied to the control collection until after OnPreInit. The only possible issues I see with this, is that

1) Your devs will have to remember this switch happens (technical debt)

2) You will have to load up both MasterPage classes every time the page is requested (performance issue)

Pete Amundson
A: 

It's a perfectly good idea. Half the point of master pages is that you can do this.

One annoying thing about them, is that you can't have them start referencing a non-existent file (which would make it clearer when you're always going to decide on the master programattically), so if I'm going to always set it to something new I like to have it start with a page that just says "Dummy master page, this will be moved from programatically", so it's clear that this is happening to anyone tracking down the masterpage used by the page.

Jon Hanna
Thanks Jon. I actually have seen this done before and never looked into why or what it was. This is a good idea and would seem to alleviate some of the future confusion that Koistya mentioned. My paranoia is abating.