RSS

[ASP.NET] [C#] Switching MasterPage Dynamically

Have you ever wanted to changed a MasterPage of an ASPX webpage dynamically when your website is running? Well, I’ve recently encountered this problem myself too and found a solution to it. So without further ado, I present the solution to you!

First go to your code-behind page of the .aspx page which you wish to have its MasterPage changed dynamically. Let’s say for example, you want your example01.aspx to change its MasterPage dynamically, you have to open the example01.aspx.cs page.

Ok here’s the step-by-step walkthrough.

Step 01:

Enter the following code below at anywhere in the public partial class section

Code:
protected void Page_PreInit(object sender, EventsArgs e)
{

}

Explanation:

The MasterPage needs to be defined before the .aspx page is initialized. In simpler terms, without the MasterPage predefined before the .aspx initialized, the .aspx page have no where to be loaded to, because webpages of website which utilizes MasterPage normally and most certainly requires a ContentPlaceHolder for it to be loaded into.

 

Step 02:

Enter the following code in the Page_PreInit body

Code:

MasterPageFile = “YourMasterPage.Master”;

 

Step 03 (optional):

Incorporate conditions with the code. What’s the point of changing MasterPage dynamically if there’s no conditions in the first place, right? The fact that we want to dynamically switch MasterPages, there has to be a condition. Therefore, incorporate them!

In my case, I determine  the user type. If the user who logs in is an admin for example, I will display a MasterPage for admins, if its a user, I’ll display a MasterPage for users.

The code should look something like this:

protected void Page_PreInit(object sender, EventArgs e)
{
     string redirect_from = ((string)Request.QueryString["redirectedfrom"]);

     if (redirect_from == "staff")
     {
          MasterPageFile = "~/MasterPage/StaffMaster.master";
    }
    else
    {
          MasterPageFile = "~/MasterPage/AdminMaster.Master";
    }
}

 

The code above shows the way I incorporated conditions to the code which triggers it to switch MasterPage if a certain user type logs in. If you’re wondering what’s with the “~/MasterPage/”, it is because I stored all my pages in their respective folders and my MasterPages are stored in a folder named MasterPage.

  • www.tips-fb.com
  • Follow LBenjamin on Twitter
  • Digg
  • Del.icio.us
  • StumbleUpon
  • Reddit
  • RSS

0 peepz:

Post a Comment