How to set the theme programmatically for the whole web site and not just a page

On my current project I am working on I needed a way for when the user selects a theme to set the whole site to the same theme.

Doing it for just one page is pretty straight forward.  Basically by setting a QueryString variable to the name of the theme and then setting the Page.Theme to the name in the Page_PreInit event it will set the page to the given theme.

pagename.aspx?theme=themename
 
protected void Page_Init(object sender, EventArgs e) {
  if (Request.QueryString.AllKeys.Contains("theme") == true) {
    Page.Theme = Request.QueryString["theme"];
  }
}

I did have some issued with using ViewState and Session so QueryString seemed to be the way to get it to work.

Setting the theme for the site and keeping it from page to page presented some issues because of the the ViewState and Session variables.  So I had to find some other method.

I have to give credit to Rick van den Bosch for his blog entry HowTo: Set the Theme for a MasterPage (from code) which is located at http://bloggingabout.net/blogs/rick/archive/2007/10/20/howto-set-the-theme-for-a-masterpage-from-code.aspx.

It had just about everything that I needed to set the theme for the whole site.  The only thing that I needed was to code a method that he called DetermineTheme.  How I accomplished that was as follows:

I first created a BasePage that inherited from System.Web.UI.Page.  Then in the page I added a property called CurrentTheme.  This will store the currently used theme for the web site.  I put that in the App_Code folder of the website.   The class is as follows:

public class BasePage : System.Web.UI.Page {
  public string CurrentTheme {
    get {
      string currentTheme = string.Empty;
      if (Session["CurrentTheme"] != null) {
        currentTheme = Session["CurrentTheme"].ToString();
      }
      return currentTheme;
    }
    set {
      Session["CurrentTheme"] = value;
    }
  }
}

Then every page for the site inherits from the BasePage as follows:

public partial class _Default : BasePage

Then in the Global.asax page in the Application_PreRequestHandlerExecute method I entered the code to set the theme.  The method looks as follows:

void Application_PreRequestHandlerExecute(object sender, EventArgs e) {
 
    var page = Context.Handler as BasePage;
    if (page != null) {
 
        if (Request.QueryString.AllKeys.Contains("theme") == true) {
            page.CurrentTheme = Request.QueryString["theme"];
        }
 
        page.Theme = page.CurrentTheme;
    }
}

This allows the theme to be changed and set for each page of the website.

Comments are closed.