Jaa


Walkthrough: Creating and Using ASP.NET Master Pages in Visual Web Developer

This walkthrough illustrates how to create a master page and several content pages. Master pages allow you to create a page layout — a template page — and then create separate pages containing content that is merged with the master page at run time. For more information about master pages, see ASP.NET Master Pages.

A Visual Studio project with source code is available to accompany this topic: Download.

Note

By default, the ASP.NET Web Site project template includes prebuilt functionality, which includes a master page. However, this walkthrough uses the ASP.NET empty Web site project template to show you how to manually add a master page to a Web site.

Tasks illustrated in this walkthrough include:

  • Creating a master page.

  • Creating an ASP.NET page that contains content that you want to display in the master page.

  • Selecting a master page at run time.

Prerequisites

In order to complete this walkthrough, you will need:

  • Visual Studio or Microsoft Visual Web Developer Express.

    Note

    If you are using Visual Studio, the walkthrough assumes that you selected the Web Development collection of settings when you started Visual Studio the first time. For more information, see How to: Select Web Development Environment Settings.

  • Optionally, a .jpg, .gif, or other graphics file that you can use as a logo on your master page. It is recommended that the logo be no more than 48 pixels wide. However, displaying a logo is optional and the graphic's exact size is not critical to the walkthrough.

Creating a Web Site

If you have already created a Web site in Visual Web Developer (for example, by following the steps in Walkthrough: Creating a Basic Web Page in Visual Studio), you can use that Web site and skip to the next section, Creating the Master Page. Otherwise, create a new Web site and page.

This walkthrough uses a Web site project. You could use a Web application project instead. For information about the difference between these Web project types, see Web Application Projects versus Web Site Projects.

To create a file system Web site

  1. Open Visual Studio or Visual Web Developer Express.

  2. In the File menu, click New Web Site.

    The New Web Site dialog box is displayed.

  3. Under Installed Templates, click Visual Basic or Visual C# and then select ASP.NET Empty Web Site.

  4. In the Web location box, select File System, and then enter the name of the folder where you want to keep the pages for your Web site.

    For example, type the folder name C:\WebSites.

  5. Click OK.

    Visual Studio creates an Web site project that includes a Web.config file.

Creating the Master Page

The master page is the template for how your pages will look. In this section, you will first create a master page. You will then use a table to lay out the master page with a menu, a logo, and a footer that will appear on each page of your site. You will also work with a content placeholder, which is a region in the master page that can be replaced with information in a content page.

To create the master page

  1. In Solution Explorer, right-click the name of your Web site, and then click Add New Item.

  2. Under Visual Studio installed templates, click Master Page.

  3. In the Name box, type Master1.

  4. Select the Place code in separate file check box.

    Note

    This walkthrough assumes you are using code-behind files for all pages. If you are using a single-file ASP.NET page, the code illustrated in this walkthrough will work, but will appear in Source view, not in a separate code file.

  5. In the Language list, click the programming language you prefer and then click Add.

    The new master page opens in Source view.

    At the top of the page is an @ Master declaration instead of the @ Page declaration normally found at the top of ASP.NET pages. The body of the page contains a ContentPlaceHolder control, which is the area of the master page where replaceable content will be merged from content pages at run time. You will work more with the content placeholder later in this walkthrough.

Laying Out the Master Page

The master page defines how the pages in your site look. It can contain any combination of static text and controls. A master page also contains one or more content placeholders that designate where dynamic content will appear when pages are displayed.

In this walkthrough, you will use a table to help you position elements on the page. You will start by creating a layout table to hold the master page elements. Later in this section you will position the content placeholder control that is already on the page.

To create a layout table for the master page

  1. With the Master1.master file selected in Source view, use the Target Schema for Validation drop-down list on the toolbar to set the target schema to Microsoft Internet Explorer 6.0.

  2. Switch to Design view.

  3. Click on the center of the page to select the page. From the Properties window, set BgColor property to a distinctive color, such as blue.

    The color you select is not important. Later in this walkthrough you will create a second master page without a color to contrast with what you have selected here.

  4. Click the page where you want to place the layout table.

    Note

    Do not put the layout table inside the ContentPlaceHolder control.

  5. On the Table menu, click Insert Table.

  6. In the Insert Table dialog box, create a table with three rows and one column, and then click OK.

  7. Place the cursor inside the second row of the table.

  8. On the Table menu, in the Modify submenu, click Split Cells.

  9. In the Split Cells dialog box, select Split into columns, and then click OK.

  10. Make the following settings:

    • In the middle row, click the leftmost column, and then set its Width to 48 in the Properties window.

    • Click the top row, and then set its Height to 48 in the Properties window.

    • Click the bottom row, and then set its Height to 48 in the Properties window.

      Note

      You can set the width and height by dragging the table cell borders or by selecting the cell and setting values in the Properties window.

  11. Select all cells in the table and set BgColor to a different color than the background color.

After laying out the table, you can add content to the master page that will appear on all pages. You will add a copyright message as a footer, and then add a menu. If you have a logo graphic available, you can add that as well.

To add static content to the master page

  1. Click the bottom cell, and then type footer text such as Copyright 2007 Contoso Inc.

  2. In the Toolbox, from the Navigation control group, drag a Menu control into the top cell.

  3. Create a menu by following these steps:

    1. Set the Menu control's Orientation property to Horizontal.

    2. Click the smart tag on the Menu control, and click Edit Menu Items in the Menu Tasks dialog box. The Edit Menu Items dialog box appears.

  4. In the Edit Menu Items dialog box, in the Items section, click the Add a root node icon twice to add two menu items:

    1. Click the first node, and then set Text to Home and NavigateUrl to Default.aspx.

    2. Click the second node, and then set Text to About and NavigateUrl to About.aspx.

    3. Click OK to close the Menu Item Editor dialog box.

  5. If you have a graphics file available to use as a logo, follow these steps to place it on the master page:

    1. In Solution Explorer, right-click the name of your Web site, and then click Add Existing Item.

    2. Navigate to your graphics file, select the graphic file, and then click Add.

    3. In the Toolbox, from the Standard group, drag an Image control to the middle left column of the table.

    4. Set the Image control's ImageUrl property to the name of the graphics file.

You can now position the content placeholder to specify where the master page can display content at run time.

To move the content placeholder

  1. Drag the ContentPlaceHolder control into the middle right cell. You can move the control by clicking inside the control and then dragging it by its tag.

    The control's ID property is ContentPlaceholder1. You can leave this name or change it. If you change the name, make a note of the name because you will need to know the name later.

  2. Save the page.

Creating Content for the Master Page

The master page provides the template for your content. You define content for the master page by creating an ASP.NET page that is associated with the master page. The content page is a specialized form of an ASP.NET page that contains only the content to be merged with the master page. In the content page, you add the text and controls that you want to display when users request that page.

In this walkthrough, you will add two pages with content for the master page. The first is a default (home) page and the second is an about page.

To create the Default page

  1. In Solution Explorer, right-click the name of your Web site, and click Add New Item.

  2. Under Visual Studio installed templates, click Web Form.

  3. In the Name box, keep the file name that Visual Studio inserts: Default.

  4. In the Language list, click the programming language you prefer.

  5. Select the Select master page check box, and then click Add.

    The Select a Master Page dialog box appears.

  6. Click Master1.master, and then click OK.

    A new .aspx file is created. The page contains an @ Page directive that attaches the current page to the selected master page with the MasterPageFile attribute, as shown in the following code example.

    <%@ Page Language="VB" MasterPageFile="~/Master1.master" ... %>
    
    <%@ Page Language="C#" MasterPageFile="~/Master1.master" ... %>
    

    The page also contains an Content control element that you will work with next.

A content page does not have the usual elements that make up an ASP.NET page, such as html, body, or form elements. Instead, you add only the content that you want to display on the master page by replacing the placeholder regions you created in the master page.

To add content to the Default page

  1. In Source view, type Contoso Home Page in the Title element of the @ Page directive at the top of the page.

    You can set the title of each content page independently, so that the correct title is displayed in the browser when the content is merged with the master page. The title information is stored in the content page's @ Page directive.

  2. Switch to Design view.

    The ContentPlaceHolder controls in the master page are displayed as Content controls in the new content page. The rest of the master page content is displayed so that you can see the layout. However, it appears dimmed because you cannot change it while you are editing a content page, and the cursor becomes the I-bar only where you can add content.

  3. In the Content control that matches ContentPlaceHolder1 on the master page, type Welcome to the Contoso Web Site.

  4. Select the text then format it as a heading by selecting Heading 1 from the Block Format drop-down list above the Toolbox.

  5. Press ENTER to create a new blank line in the Content control, and then type Thank you for visiting our site.

    The text you add here is not important; you can type any text that will help you recognize this page as the Default (home) page.

  6. Save the page.

You can create the About page the same way you created the Default page.

To create the About page

  1. Use the same steps that you used for the Default page to add a new content page named About.aspx.

    Be sure to attach the new page to the Master1.master page as you did with the Default page.

  2. Change the page's title to Contoso About Page.

  3. In the content region, type About Contoso, and then format the text as a Heading 2 by selecting the text and selecting Heading 2 from the Block Format drop-down list above the Toolbox.

  4. Press ENTER to create a new line, and then type Since 1982, Contoso has provided high-quality software services.

  5. Save the page.

Testing the Pages

You can test the pages by running them as you would any ASP.NET page.

To test the pages

  1. Switch to the Default.aspx page, and then press CTRL+F5.

    ASP.NET merges the content in the Default.aspx page with the layout in the Master1.master page into a single page and displays the resulting page in the browser.

  2. Click the About link.

    The About.aspx page is displayed. It is also merged with Master1.master page.

Referencing Master Page Members

Code in the content pages can reference members on the master page, including any public properties or methods and any controls on the master page. In this part of the walkthrough, you will create a property on the master page, and then use the value of the property in the content pages. The premise is that the company name for the Web site is stored as a property in the master page, and any reference to the company name in the content pages is based on the master page property.

The first step is to add a property to the master page.

To add a property to the master page

  1. Switch to or open the Master1.master page.

  2. In Solution Explorer, right-click Master1.master, and then click View Code to open the code editor.

    Note

    By default, Visual Web Developer creates pages that use the code-behind model.

  3. Inside the class definition, type the following code.

    Public Property CompanyName() As String
        Get
            Return CType(ViewState("companyName"), String)
        End Get
        Set(ByVal Value As String)
            ViewState("companyName") = Value
        End Set
    End Property
    
    public String CompanyName
    {
        get { return (String) ViewState["companyName"]; }
        set { ViewState["companyName"] = value; }
    }
    

    The code creates a property named CompanyName for the master page. The value is stored in view state so that it is persisted between postbacks.

  4. Inside the class definition (but not inside the property code), add the following code.

    Sub Page_Init(ByVal sender As Object, ByVal e As EventArgs) _
           Handles Me.Init
       Me.CompanyName = "Contoso"
    End Sub
    
    void Page_Init(Object sender, EventArgs e)
    {
       this.CompanyName = "Contoso";
    }
    

    For this example, you will hard-code the value of the CompanyName property into the page.

You can now modify the content page to use the master page's CompanyName property.

To reference the CompanyName property in the content page

  1. Switch to or open the Default.aspx page.

  2. Switch to Source view.

  3. At the top of the page, underneath the @ Page directive, add the following @ MasterType directive:

    <%@ MasterType virtualpath="~/Master1.master" %>
    

    The directive binds the content page's Master property, which you will use shortly, to the Master1.master page.

  4. Switch to Design view.

  5. In the Content control, change the text to Welcome to the Web site of .

  6. In the Toolbox, from the Standard group, drag a Label control onto the Content control, and place it after the static text so that the text reads:

    Welcome to the Web site of [Label]

  7. Set the Label control's ID property to CompanyName.

  8. In Solution Explorer, right-click Default.aspx, and then click View Code to open the code editor.

  9. Inside the class definition, add the following code.

    Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) _
            Handles Me.Load
        CompanyName.Text = Master.CompanyName
    End Sub
    
    void Page_Load(Object sender, EventArgs e)
    {
       CompanyName.Text = Master.CompanyName;
    }
    

    The content page's Master property returns a reference to the master page as defined in the @ MasterType directive you added in step 3.

You can now test the content page to be sure it is referencing the master page's CompanyName property correctly.

To test the reference to the master page property

  1. Switch to or open the Default.aspx page, and then press CTRL+F5 to run the page.

    The page is displayed in the browser, with the text Welcome to the Web site of Contoso

  2. Close the browser.

  3. Switch to or open the Master1.master code-behind page.

  4. Change the Page_Init handler to assign a different company name to the property, as in the following code example.

    Sub Page_Init(ByVal sender As Object, ByVal e As EventArgs) _
           Handles Me.Init
       Me.CompanyName = "New Company Name"
    End Sub
    
    void Page_Init(Object sender, EventArgs e)
    {
       this.CompanyName = "New Company Name";
    }
    
  5. Switch to the Default.aspx page, and then press CTRL+F5 to run it again.

    This time, the updated company name appears in the page.

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

  1. In Solution Explorer, right-click Master1.master, and then click Copy.

  2. 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.

  3. Right-click Copy of master1.master, click Rename, and then name the new master page Master2.master.

  4. 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" %>
    
  5. Switch to Design view.

  6. In the Properties window, in the drop-down list at the top, click DOCUMENT.

  7. Change the BgColor property to a color visibly different than the color you chose for Master1.

    The new master page will look and function like Master1.master, but will have a different background color.

  8. 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:

    Partial Class Master2
    
    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

  1. Switch to or open the Master2.master page.

  2. 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.

  3. Set the button's Text property to First Color.

  4. 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
    
    protected 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.

  5. Switch to or open the Master1.master page in Design view.

  6. Add a LinkButton control as you did in steps 1 and 2, and set its Text property to Second Color.

  7. 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
    
    protected 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 can 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

  1. Switch to or open the About.aspx page.

    Note

    The Default 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 Default page and will instead work with other pages you have created.

  2. In Solution Explorer, right-click About.aspx, and then click View Code to open the code editor.

  3. 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

  1. 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.

  2. Click the Second Color link.

    The page is redisplayed, this time merged with Master2.master, which has no background color.

  3. Click the First Color 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.

  • You need to add the code from the Default.aspx page to every page where you want to override the default master page.

Next Steps

This walkthrough illustrates the basic functionality of master pages. You might want to experiment with additional features of master pages. For example, you might want to:

  • Create master pages that have multiple content placeholders. You can then fill one or more placeholders with content for each page that you display.

  • Define content placeholders with default content. If an ASP.NET page does not supply content for the placeholder, the master page displays the default content.

  • Programmatically access members of the master page from content pages. This allows you to dynamically change the look of the master page at run time. For details, see How to: Reference ASP.NET Master Page Content.

  • Use device filtering with master pages to create different layouts for different devices, such as one layout for browsers and another for a specific type of phone. For details, see ASP.NET Device Filtering Overview.

  • Learn how you can put master pages within master pages to create componentized pieces. For details, see Nested ASP.NET Master Pages.

See Also

Concepts

Events in ASP.NET Master and Content Pages

Other Resources

ASP.NET Master Pages