Wednesday, June 15, 2011

Dynamic Themes in MVC and handling Page_PreInit

Another thing I learnt at Resonate Solutions:
Generally, when you create an MVC Application the project template will provide a Master Page that can be referenced by any Views you create.
That means when you want to implement generic code that executes for all page loads, typically the most logical place to put it is in the Master Page's code behind.
This would be ideal if you were to implement the following code to set a theme dynamically (based on the themes in the App_Theme folder):

this.Page.Theme = Request.QueryString["Theme"];
The page's theme, however, is processed during the initialization stage of the page's life cycle, and therefore if we need to set it, it must be done before hand i.e. in the OnPreInit event handler.
The problem is that the Master Page doesn't actually have an OnPreInit event because it isn't actually a page in its own right.
It is a user control that merges with the content page during the initialization phase of the page's processing, so just like a UserControl it wouldn't have an OnPreInit.
So therein lies our problem. Rather than copying and pasting the above code for every single View. We would need to create a BaseViewPage that is inherited by all the Views.
Take note that all Views inherit off the following class:

namespace Hub.Samples.Mvc
    public class BaseViewPage<T> : ViewPage<T> where T : class
        this.Page.Theme = Request.QueryString["Theme"];

That also means that each View we create needs to inherit off it. This can obviously be done in the page directive as follows:

<%@ Page Inherits="Hub.Samples.Mvc.BaseViewPage<dynamic>" %>