Tip #40: Did you know…How to scope master pages?

Master page is a  template page that can be used to create a consistent layout for your application. First you create a master page to define the look & feel of the application and then you create the content pages that contains the content.

You can attach these content pages to the master page at the following three levels:

  1. Page Level: You can use the page directive on each of the content pages

    <@Page Language="VB" MasterPageFile="~/Main.master"%>

    Or programmatically set it in the content page Page_PreInit Event

    for VB
    Protected Sub Page_PreInit(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.PreInit
            Me.MasterPageFile = "~/Main.master"
    End Sub

    for C#
    protected void Page_PreInit(Object sender, EventArgs e)
            {
                this.MasterPageFile = "~/Main.Master";
            }

  2. Application Level : By specifying the following in web.config file, all the aspx files will use the master page as Main.master (If  aspx file does not contain a Content control, the master page won't be applied to it )

    <configuration>
        <system.web>
                   <pages masterPageFile="~/Main.master" />
       </system.web>
    </configuration>

    [You will notice that the pages node already exists in web.config, add the masterPageFile attribute to this node]

  3. Folder Level: By specifying the following in web.config all the aspx files in a specified folder (admin) will use the master page as Admin.master (If  aspx file does not contain a Content control, the master page won't be applied to it )

    <configuration>
        <location path="admin">
        <system.web>
                   <pages masterPageFile="~/Admin.master" />
       </system.web>
       </location>
    </configuration>

    [you will notice system.web already exists, leave it as it is & add a new node 'location' with the above content under 'configuration']

By setting master page programmatically or thru web.config you may not get the Visual Studio master page design time features.

 

Deepak Verma
SDET | Visual Web Developer