ASP.NET Theme across all pages with XMLHttpRequest calls

ASP.NET Themes is very powerful feature, but some limitations exist when you are trying to apply Themes dynamically.

For the single page the way to apply theme is to use

Page.Theme = “<themeName>”;

inside  the OnPreInit event, but if you try to apply theme for all pages across your site you have two solutions:

  1. add this code to each of the pages
  2. apply theme for master.page – and it’s where problem starts

ASP.NET master pages don’t support applying themes dynamically – only static support for the all site pages by setting attribute inside web.config.

But what to do if you need control which theme to apply and you don’t want to add code to every page of your site?!

The solution for this to create custom HttpModule, where apply theme for Page class inside PreRequestHandlerExecute event.

See the following code-snippet of the ThemeHttpModule

   1: public void Init(HttpApplication context)
   2: {
   3:     context.PreRequestHandlerExecute += context_PreRequestHandlerExecute;
   4: }
   5:  
   6: void context_PreRequestHandlerExecute(object sender, EventArgs e)
   7: {
   8:     HttpContext context = HttpContext.Current;
   9:     if (!(context.Handler is Page))
  10:     {
  11:         return;
  12:     }
  13:  
  14:     Page page = (Page)context.Handler;
  15:     
  16:     if ((page != null))
  17:     {
  18:         string themeName = "Default";  // get theme name from somewhere
  19:         page.Theme = themeName;
  20:     }
  21: }

Done. Now you have flexible control which theme to apply in realtime, extracting you theme names from config or from database.

But there is one case, I’d like point you attention – XMLHttpRequest calls.

If you have AJAX XMLHttpRequest direct calls – this code won’t work, because server returns you only portion of page, not the full page with header and body. And you can’t apply theme on partial pages.

To solve this you need to check if it’s partial request or not, inside your HttpModule. In case of ASP.NET AJAX you could use ScriptManager.IsInAsyncPostBack, but for the direct XMLHttpRequest  calls you need to check the header for the Content-Type you are used when create the MSXML object.

Something like this

   1: // Don''t apply theme for XMLHttpRequest calls, because you are getting part of the page,not the full page
   2: if (! string.IsNullOrEmpty(context.Request.ContentType))
   3: {
   4:     return;
   5: }

Now your themes will be applied only on pages,not the partial AJAX calls.

 

Mirror: ASP.NET Theme across all pages with XMLHttpRequest calls

2 Comments »

  1. Darren Neimke Said,

    July 28, 2008@ 9:21 pm      Reply

    Nice tip… thanks for sharing Michael!

  2. Ankit Joshi Said,

    October 23, 2009@ 12:36 pm      Reply

    Nice bro,
    Its helps me a lot


RSS feed for comments on this post · TrackBack URI

Leave a Comment