Changing Master Page at Runtime

Solution 1:
Changing Master Page at Runtime by user code.
Many times we have to change Master Page at Runtime by user code. Page_PreInit event will execute just before that page is render. We can write a simple code in Page_PreInit event like below,

protected void Page_PreInit(object sender, EventArgs e) 
{ 
     if (Membership.GetUser() == null)         //check if the user is logged in or not
               this.MasterPageFile = "~/General.master";
     else
               this.MasterPageFile = "~/MyPortal.master";
}
Solution 2: 
Changing Master Page at Runtime by user code based on users roles and responsibilities.

Sometimes there different types of users for the same application. All users have their own roles and responsibilities for the  application.

For e.g  There are different types of users for my portal application. They all should be able to browse their role related master page.
1.    Executive Directors
2.    Admin
3.    Investment Officers
4.    Users
For above portal application senerio we can write code in content Page_PreInit event like below,
protected void Page_PreInit(object sender, EventArgs e)
{ 
          int varRole = 0;
          int.TryParse(Session["Role"].ToString(),out varRole);

          if (varRole == 1)
          {
                  this.MasterPageFile = "ExecDir.master";
          }
          if (varRole == 2)
          {
                  this.MasterPageFile = "Admin.master";
          }
          if (varRole == 3)
          {
                  this.MasterPageFile = "Officer.master";
          } 
          if (varRole == 4)
          {
                  this.MasterPageFile = "User.master";
          }
 }

No comments:

Post a Comment