Dynamically Changing MasterPage

Changing MasterPage Dynamically

In real-time we may come across scenario where depending on the particular group of users we need to show different layout, colors, themes, functionalities and so on. To achieve this there are various ways, maintain the settings for each user in table , maintain the cookies and so on.

 In .net the best way to achieve this is to change master page dynamically where the master pages will have different layout , different look and feel for different users.  This we can achieve by following below mentioned steps.

1.       All the WebPages will be inherited form System.UI.Web.Page base class

2.       In page directive we  have a property to set masterpage file

3.       Once we attach any master page to any child, first all the controls of the master page are instantiated, then child page controls are instantiated

4.       If we want to apply master page in code behind file ,the page’s master page property needs to be applied in Onpreinit method only.

5.       After instantiating controls, child page load will be called first, then the master page will be loaded.

To change master page dynamically we need to follow the below mentioned process/method

1.       Create one separate class file as public, which will inherits System.UI.Web.Page base class

2.       Override the Page base class method onPreinit(), in this method set the master page property of the page, give the name of the master page file which you want to apply

3.       At the end of the onPreinit() method call the base class onpreinit method

4.       Inherit the newly created class in all of your web pages.

5.       To provide the custom master page, we may use cookies, sessions or the values stored from database, it depends on how we want to manage the customization.

 

Illustration

Illustration

 

 

Did you enjoy this post? Why not leave a comment below and continue the conversation, or subscribe to my feed and get articles like this delivered automatically to your feed reader.

Comments

Thank you! It helped me !

Leave a comment

(required)

(required)