1.4. Setting the Master Page at Runtime

Problem

You have an application where you need to change the assignment of the master pages used at runtime.

Solution

Create the desired master/content pages as described in Recipes 1.1 and 1.2. In the Page_ PreInit event handler of code-behind for the content pages, set the Page.MasterPageFile property to the name of the desired .master file.

Example 1-8 shows the .aspx file, and Examples 1-9 and 1-10 show the VB and C# code-behind files for our application.

Discussion

Many applications need the ability to change the appearance of the rendered pages as a function of many factors such as a different look for the seasons or for client branding. Using master pages and changing the assigned master page at runtime can meet the requirements of these applications.

With ASP.NET 2.0, the Page class has a new MasterPageFile property that can be set at runtime to change the master page used to render the content page. The MasterPageFile property must be set before ASP.NET begins processing the page. The Page_PreInit event occurs immediately before the page processing occurs and is the last opportunity to change the master page that will be used to render the page.

Tip

Setting the MasterPageFile property at any point in the page processing after the Page_PreInit event results in an exception being thrown, indicating the MasterPageFile property cannot be set after the Page_PreInit event.

The Page class has a new read-only Master property that can be used to access the MasterPage object. Through the MasterPage object, you can access any public properties or methods of the master page. If you have added public properties or methods to your master pages that you need to access in your content pages, you will need to cast the MasterPage object to the class type of your master page as shown below for a pageHeading property.


	CType(Page.Master, ASPNetCookbookVB_master).pageHeading = "Test Heading"

	((ASPNetCookbookCS_master)Page.Master).pageHeading = "Test Heading";

In our example, we have stored the name of the master page that will be set at runtime in the web.config as shown below. In your application, you might want to obtain the master page information from a database or any other data store that your application needs:


	<appSettings>
          <add key="runtimeMasterPage" value="CH01MasterPage1VB.master" />
    </appSettings>


	<appSettings>
	<add key="runtimeMasterPage" value="CH01MasterPage1CS.master" />
	</appSettings>

In the Page_PreInit event handler, we read the master page name from the web.config file and set the MasterPageFile property:


	Private Sub Page_PreInit(ByVal sender As Object, _
                             ByVal e As System.EventArgs) Handles Me.PreInit
      Dim masterPage As String

	  'get name of master page from web.config
	  masterPage = ConfigurationManager.AppSettings("runtimeMasterPage")

	  'set the master page to be used with this page
	  Page.MasterPageFile = masterPage
    End Sub 'Page_PreInit


	private void Page_PreInit(Object sender,
                              System.EventArgs e)
    {
      String masterPage = null;

	  //get name of master page from web.config
	  masterPage = ConfigurationSettings.AppSettings["runtimeMasterPage"];

	  //set the master page to be used with this page
	  Page.MasterPageFile = masterPage;
    } //Page_PreInit

See Also

Recipes 1.1 and 1.2

Example 1-8. Setting the master page at runtime (.aspx)

<%@ Page Language="VB" MasterPageFile="~/ASPNetCookbookVB.master"
     AutoEventWireup="false" 
	 CodeFile="CH01SetMasterPageAtRuntimeVB.aspx.vb" 
	 Inherits="ASPNetCookbook.VBExamples.CH01SetMasterPageAtRuntimeVB" 
	 title="Set Master Page At Runtime" %>
<asp:Content ContentPlaceHolderID="PageBody" Runat="Server"> 
     <div align="center" class="pageHeading">
          Set Master Page At Runtime (VB)
     </div>
	 <br />
	 <br />
	 <p align="center">The content for your pages is placed here.</p>
</asp:Content>

Example 1-9. Setting the master page at runtime (.vb)

Option Explicit On 
Option Strict On 
Namespace ASPNetCookbook.VBExamples
  ''' <summary>
  ''' This class provides the code behind for
  ''' CH01SetMasterPageAtRuntimeVB.aspx
  ''' </summary>
  Partial Class CH01SetMasterPageAtRuntimeVB
    Inherits System.Web.UI.Page

	'''*********************************************************************** 
	''' <summary>
	''' This routine provides the event handle for the page preinit
	''' event.  It is responsible for setting the master page file
	''' using a setting is the app settings section of web.config
	''' </summary>
	'''
	''' <param name="sender">Set to the sender of the event</param>
	''' <param name="e">Set to the event arguments</param>
	Private Sub Page_PreInit(ByVal sender As Object, _
										ByVal e As System.EventArgs) Handles Me.PreInit
      Dim masterPage As String

	  'get name of master page from web.config
	  masterPage = ConfigurationManager.AppSettings("runtimeMasterPage")

	  'set the master page to be used with this page
	  Page.MasterPageFile = masterPage
    End Sub 'Page_PreInit
  End Class 'CH01SetMasterPageAtRuntimeVB 
End Namespace

Example 1-10. Setting the master page at runtime (.cs)

using System; 
using System.Configuration;

namespace ASPNetCookbook.CSExamples
{ 
  /// <summary> 
  /// This class provides the code behind for 
  /// CH01SetMasterPageAtRuntimeCS.aspx 
  /// </summary> 
  public partial class CH01SetMasterPageAtRuntimeCS : System.Web.UI.Page 
  {

    ///*********************************************************************** 
	/// <summary>
	/// This routine provides the event handle for the page preinit
	/// event.  It is responsible for setting the master page file
	/// using a setting is the app settings section of web.config
	/// </summary>
	///
	/// <param name="sender">Set to the sender of the event</param>
	/// <param name="e">Set to the event arguments</param>
	private void Page_PreInit(Object sender,
                                         System.EventArgs e)
    {
      String masterPage = null;

	  //get name of master page from web.config
	  masterPage = ConfigurationSettings.AppSettings["runtimeMasterPage"];

	  //set the master page to be used with this page
	  Page.MasterPageFile = masterPage;
    }  //Page_PreInit
  } // CH01SetMasterPageAtRuntimeCS 
}

Get ASP.NET 2.0 Cookbook, 2nd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.