
Changing Master Pages Dynamically
Under some circumstances, you might want to be able to change master pages dynamically; that is, to use code to set the master page for a content page. For example, you might want to let users select from several layouts and set the master page according to their preferences.
In this part of the walkthrough, you will add a second master page to the Web site, and then create buttons that allow the user to switch between one master page and another. Because the two master pages will be very similar, you will make a copy of the first master page and modify it to act as the second master page.
To make a copy of the master page
In Solution Explorer, right-click Master1.master, and then click Copy.
Right-click the name of the Web site, and then click Paste.
A master page is added to the Web site with the name Copy of master1.master.
Right-click Copy of master1.master, click Rename, and then name the new master page Master2.master.
Open Master2.master and, in the @ Master directive, change Master1 to Master2.
The completed page directive will look like the following code example:
<%@ Master Language="VB" CodeFile="Master2.master.vb" Inherits="Master2" %>
<%@ Master Language="C#" CodeFile="Master2.master.cs" Inherits="Master2" %>
Switch to Design view.
In the Properties window, in the drop-down list at the top, click DOCUMENT.
Clear the BgColor property.
The new master page will look and function like Master1.master, but will have no background color.
Open the code file for Master2.master and change the class name in the master page's code-behind file from Master1 to Master2 to match the value of the Inherits attribute in the page's @ Master directive.
The code will look like the following example:
public partial class Master2 : System.Web.UI.MasterPage
The next step is to add a button to each master page that allows the user to select the alternate master page.
To add buttons for selecting an alternate master page
Switch to or open the Master2.master page.
In the Toolbox, from the Standard node, drag a LinkButton control onto the page and place it below the menu in the top table cell.
Set the button's Text property to Colorful.
Double-click the button to create a handler for its Click event, and then add the following highlighted code.
Protected Sub LinkButton1_Click(ByVal sender As Object, ByVal e As EventArgs)_
Handles LinkButton1.Click
Session("masterpage") = "Master1.master"
Response.Redirect(Request.Url.ToString())
End Sub
[C#]
void LinkButton1_Click(Object sender, EventArgs e)
{
Session["masterpage"] = "Master1.master";
Response.Redirect(Request.Url.ToString());
}
The code loads the file name of the alternate master page into a persistent session variable, and then reloads the current page. (The Url property returns a Uri object that references the current page.) Shortly, you will create code in the content page that will use the name of the master page.
Switch to or open the Master1.master page in Design view.
Add a LinkButton control as you did in steps 1 and 2, and set its Text property to Plain.
Double-click the Plain button to create a handler for its Click event, and then add the following highlighted code.
Protected Sub LinkButton1_Click(ByVal sender As Object, ByVal e As EventArgs)_
Handles LinkButton1.Click
Session("masterpage") = "Master2.master"
Response.Redirect(Request.Url.ToString())
End Sub
void LinkButton1_Click(Object sender, EventArgs e)
{
Session["masterpage"] = "Master2.master";
Response.Redirect(Request.Url.ToString());
}
This code is the same as that for the button in the Master2.master page, except that it loads an alternate master page.
You now write code in the content page that will dynamically load the master page that the user has selected.
To write code to dynamically select the master page
Switch to or open the About.aspx page.
Note: |
|---|
The Home page you have already created contains an
@ MasterType directive that effectively binds it to a single master page (Master1.master). Therefore, you will not be able to assign master pages dynamically to the Home page and will instead work with other pages you have created.
|
In Solution Explorer, right-click About.aspx, and then click View Code to open the code editor.
Inside the class definition, add the following code.
Sub Page_PreInit(ByVal sender As Object, ByVal e As EventArgs) _
Handles Me.PreInit
If Not Session("masterpage") Is Nothing Then
Me.MasterPageFile = CType(Session("masterpage"), String)
End If
End Sub
void Page_PreInit(Object sender, EventArgs e)
{
if(Session["masterpage"] != null)
{
this.MasterPageFile = (String) Session["masterpage"];
}
}
The code sets the value of the current page's MasterPageFile property to the value in the session variable, if any. This code must run in the Page_PreInit handler; it cannot run in a handler that occurs any later than the Page_PreInit handler (for example, in the Page_Init handler), because the master page must be established so that the page can create an instance of it before any further initialization can occur.
You can now test the dynamic master pages.
To test the dynamic master pages
In the About.aspx page, press CTRL+F5 to run the page.
The page is displayed in the browser merged with its default master page, Master1.master.
Click the Plain link.
The page is redisplayed, this time merged with Master2.master, which has no background color.
Click the Colorful link.
The page is displayed using Master1.master again.
Notes on Using Master Pages
There are several other issues you should be aware of when working with a master page:
In a real-world application, you would probably store information such as the company name in the configuration file and read it directly in the content pages. However, the scenario outlined here provides a simple illustration of how to reference master page members in content pages.
You can access members on the master page even without including an @ MasterType directive. However, to do so, you must cast the Page..::.Master property to the appropriate master page type (the Master property is null if a page has no master page). For more information, see Working with ASP.NET Master Pages Programmatically.
You can reference controls on the master page by using the Master.FindControls method. For more information, see Working with ASP.NET Master Pages Programmatically.
There are several other issues you should be aware of when working with dynamic master pages:
The scenario in this section for changing master pages is simplified to keep the walkthrough focused on master pages. In a real application, you would most likely display a choice of layouts, and then store the user's preference by using profiles. For details, see ASP.NET Profile Properties Overview.
You can configure your Web site so that all pages use the same master page. You might have a few pages that should use an alternate master page, which you can configure in code in a manner similar to that shown in this section of the walkthrough. For details, see "Scoping Master Pages" in ASP.NET Master Pages Overview.
You need to add the code from the Home.aspx page to every page where you want to override the default master page.