Geeks With Blogs
Chris Smith My blog for anything tech

So recently I had an ASPX page that could be visited by two different user types.  User type A would use Master Page 1 and user type B would use Master Page 2.  So I put together a proof of concept to see if it was possible to change the MasterPage in code.  I found a great article on the Microsoft ASP.net website.

Specifying the Master Page Programmatically (C#) by Scott Mitchell

So I created a MasterPage call Alternate.Master to act as a generic place holder.  I also created a Master1.Master and a Master2.Master.  The ASPX page, Default.aspx will use this MasterPage.  It will also use the Page_PreInit event to programmatically set the MasterPage. 

   1:  protected void Page_PreInit(object sender, EventArgs e) {
   2:      var useMasterPage = Request.QueryString["use"];
   3:      if (useMasterPage == "1")
   4:          MasterPageFile = "~/Master1.Master";
   5:      else if (useMasterPage == "2")
   6:          MasterPageFile = "~/Master2.Master";
   7:  }

 

In my Default.aspx page I have the following links in the markup:

   1:  <p>
   2:      <asp:HyperLink runat="server" ID="cmdMaster1" NavigateUrl="~/Default.aspx?use=1" Text="Use Master Page 1" />
   3:  </p>
   4:  <p>
   5:      <asp:HyperLink runat="server" ID="cmdMaster2" NavigateUrl="~/Default.aspx?use=2" Text="Use Master Page 2" />
   6:  </p>

So the basic idea is when a user clicks the HyperLink to use Master Page 1, the default.aspx.cs code behind will set the property MasterPageFile to use Master1.Master.  The same goes with the link to use Master Page 2. 

It worked like a charm! 

To see the actual code, feel free to download a copy here:

Project Name: Skyhook.MultipleMasterPagesWeb
http://skyhookprojectviewer.codeplex.com

Posted on Wednesday, November 28, 2012 2:49 PM | Back to top


Comments on this post: 1 ASPX Page, Multiple Master Pages

No comments posted yet.
Your comment:
 (will show your gravatar)


Copyright © csmith18119 | Powered by: GeeksWithBlogs.net