ASP.NET MVC Theme Supported Razor View Engine

Recently, I was trying to add theme support in one of my pet project. There are already few articles available in ASP.NET MVC ViewEngine theming  which you will find by Google/Bing, but those are not best fitted in my case. One of the goal in theming I wanted to implement is to add fallback support, which means if a theme does not have the required file it will automatically redirect to the default version, in this way the new theme would only contain the changed files. The next thing that I wanted is simple xcopy theme deployment. Here is the structure of the Views folder of ASP.NET MVC default template when theming applied:

ASP.NET MVC Themed Views Folder
Figure 1: Views Folder

As you can see, the folder structure is almost same except there is a Themes folder where the themes resides. Setting up the view engine is trivial, the following shows the code:

              public static void RegisterViewEngine(ViewEngineCollection viewEngines)
                  // We do not need the default view engines
                  var themeableRazorViewEngine = new ThemeableRazorViewEngine
                                                         CurrentTheme = httpContext => httpContext.Session["theme"] as string ?? string.Empty
              protected void Application_Start()

The last thing I want is to separate out the current theme detection logic from the actual view engine, this is the reason the view engine uses Func<HttpContextBase, string> for detecting the current theme. The benefits of this, as HttpContext is used you can use session, cookie, profile, domain name etc. or your wild custom logic for the theme detection. Here are screenshots when the view engine is in action:

Red Theme Green Theme Purple Theme No Theme
Figure 2: Themed View Engine in Action

Though it has both Webform and Razor View Engine but the above sample is created with Razor.

Although the ASP.NET MVC is hitting version 3, but still creating a theme engine requires copying most of the functions of the core framework which the team should seriously think, it should be extensible enough just to tweak few parameters, or maybe in future I will demonstrate such thing which does not requires creating a view engine from the start.

That’s it for today.


Shout it


blog comments powered by Disqus