HowTo: Set the Theme for a MasterPage (from code)
By rickvdbosch
- 2 minutes read - 240 wordsThe MasterPage doesn’t have a property for setting the Theme at design time. Despite this, I wanted to set the Theme for a MasterPage, so I decided to set it from code. I was aware of the possibility to set the Theme through the web.config, but that wasn’t the way I wanted to set it. One of the reasons being it would result in the theme being applied to the entire website.
I tried to use the Page_Load, but that resulted in the error “The ‘Theme’ property can only be set in or before the ‘Page_PreInit’ event.”. That sounds logical, because the Theme makes the Page render in a specific way. So I added a Page_PreInit method with the right parameters, but that didn’t do anything. As it turns out, the Master Page doesn’t have a Page_PreInit…
To be able to set the Theme for a MasterPage from code, follow these steps:
- Add a class with the name ThemeModule (or any other name)
- Let the class inherit from IHttpModule
-
Implement the init method as follows: public void Init(HttpApplication context){ context.PreRequestHandlerExecute += HandlePreRequest;}
- Add the HttpModule to your web application through the web.config:
«/span>httpModules> «/span>add name=“ThemeModule“ type=“Howtos.ThemeModule“/> </httpModules>
That’s it! Hope this helps.
A week ago I came up with this solution together with a good friend of mine. The code was on his machine, so he said I had to add a ’thanks to’ in this post. Well, here it is: thanks 2 Sander van Kemenade! 😉
- Add the HttpModule to your web application through the web.config:
-
- Let the class inherit from IHttpModule