Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting an ASP.NET Master Page at runtime

I'm working on a site which needs to be able to support two or more looks, changable at runtime. I'd hoped to be able to handle the change with a CSS switch, but it looks like I'll need to use a different masterpage for each design.

So, what's the best way to set the masterpage at runtime? Page.MasterPageFile can only be set in the Page.OnPreInit event. It looks like the solutions are to make all my pages inherit from a common base which handles the PreInit event, or to use an HttpModule which does that.

Any advice?

like image 288
Jon Galloway Avatar asked Aug 18 '08 21:08

Jon Galloway


People also ask

Can we set master page dynamically at runtime?

Yes. You can assign a master page dynamically during the PreInit stage. Because the master page and content page are merged during the initialization stage of page processing, a master page must be assigned before then.

On which page event we set the MasterPageFile property?

The Page class in the System. Web. UI namespace includes a MasterPageFile property that returns the path to the content page's master page; it is this property that is set by the @Page directive. This property can also be used to programmatically specify the content page's master page.


2 Answers

Rather than two different master pages how about having one master that dynamically loads different user controls and content HTML literals?

like image 36
Keith Avatar answered Oct 03 '22 05:10

Keith


I've done this once before, I did exactly what you described (Made all pages inherit from a custom page with an OnPreInit event). Also I had a custom Application_PreRequestHandlerExecute in my Global.asax.cs for setting Page.StyleSheetTheme for doing image/css changes that didn't require a different Master Page.

like image 193
thelsdj Avatar answered Oct 03 '22 05:10

thelsdj