Monday, June 6, 2011

asp.net : Implement theme for web application using global.asax file

A theme is a collection of property settings that allow you to define the look of pages and controls, and then apply the look consistently across pages in a Web application, across an entire Web application, or across all Web applications on a server.
Themes are made up of majorly by cascading style sheets (CSS), images, and other resources like skins. . Themes are defined in special directories in your Web site or on your Web server App_Themes

How to implement

Theme can only be applied on page while Pre_Init is under execution. One way is to keep the code to implement theme in all the pages or add into global.asax file.
Global.asax File
void Application_PreRequestHandlerExecute(object src, EventArgs e)
   {
       Page _currentPageInRequest = this.Context.Handler as Page;
       if (_currentPageInRequest != null)
       {
           _currentPageInRequest.PreInit += new EventHandler(page_PreInit);
       }
   }

void page_PreInit(object sender, EventArgs e)
   {
       Object _curSessionKey=HttpContext.Current.Session["CurrentTheme"];
       if (_curSessionKey != null && (!string.IsNullOrEmpty(_curSessionKey.ToString())))
       {
           Page _currentPageInRequest = this.Context.Handler as Page;
           _currentPageInRequest.Theme = _curSessionKey.ToString();
       }
       else
       {
           Page _currentPageInRequest = this.Context.Handler as Page;
           _currentPageInRequest.Theme = "Default";
       }
   }
In above implementation, i have used Session variable to store current applied theme. You can use any mode of saving/reading of current theme. For example, database can be used to store current theme.

No comments:

Post a Comment