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.
Tasks illustrated in this walkthrough include:
·
Creating a master page.
·
Creating an ASP.NET page with content that you want to display in
the master page.
·
Running master pages to show different content.
·
Selecting a master page at run time.

In order to complete this walkthrough, you will
need:
·
Visual Studio or Microsoft Visual Web Developer Express Edition.
·
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.

Create a new Web site and page by following
these steps.
To create a file system Web
site
1.
Open Visual Web Developer.
2.
On the File menu,
click NewWeb Site.
The New Web
Site dialog box appears.
3.
Under Visual Studio installed
templates, click ASP.NET Web Site.
4.
In the Location box,
enter the name of the folder where you want to keep the pages of your Web site.
For example, type the folder name C:\WebSites.
5.
In the Language list,
click the programming language you prefer to work in.
6.
Click OK.
Visual Web Developer creates the folder and a
new page named Default.aspx.
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 AddNew
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.
![]() |
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.

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, set the target schema for
validation to Microsoft Internet Explorer 6.0. To set this value, you can use
either the drop-down list on the toolbar or select Options from the Tools menu, and then click Validation.
2. Switch to
Design view.
3. From the
drop-down list at the top of the Properties window, select DOCUMENT, and then set BgColor 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.
![]() |
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.
![]() |
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, and set VAlign to top.
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:
a. Set the
Menu control's Orientation property to Horizontal.
b. Click the
smart tag on the Menu control, and click Edit Menu Items in the Menu
Tasks dialog
box.
4. Under Items, click the Add a
root node icon
twice to add two menu items:
a. Click the
first node, and then set Text to Home and NavigateUrl to Home.aspx.
b. Click the
second node, and then set Text to About and NavigateUrl to About.aspx.
c. 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:
a. In
Solution Explorer, right-click the name of your Web site, and then click Add
Existing Item.
b. Navigate
to your graphics file, select the graphic file, and then click Add.
c. In the Toolbox, from the Standard group, drag an Image
control to the middle left column of the table.
d. 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 add a
content placeholder
1. Drag the
ContentPlaceHolder control into the middle right cell.
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.

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 home page and the second is an about page.
To create
the Home 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, type Home.
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="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 Home page
1. 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.
2. From the
drop-down list in the Properties window, click DOCUMENT, and then set Title to Contoso
Home 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.
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 home page.
6. Save the
page.
You can
create the About page the same way you created the Home page.
To create
the About page
1. Use the
same steps that you used for the Home 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 Home
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 1 by
selecting the text and selecting Heading 1 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.

You can
test the pages by running them as you would any ASP.NET page.
To test
the pages
1. Switch to
the Home.aspx page, and then press CTRL+F5.
ASP.NET
merges the content in the Home.aspx page with the layout in the Master1.master
page into a single page and displays the resulting page in the browser. Notice
that the URL of the page is Home.aspx; there is no reference in the browser to
the master page.
2. Click the
About link.
The
About.aspx page is displayed. It is also merged with Master1.master page.

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.
![]() |
By
default, Visual Web Developer creates pages that use the code-behind model.
If you prefer, you can create code by using the single-file model.
|
3.
Inside the class definition, type the following code.
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.
void
Page_Init(Object sender, EventArgs e)
{
this.CompanyName = "Contoso";
}
|
5.
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 Home.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" %>
|
4.
The directive binds the content page's Master property,
which you will use shortly, to the Master1.master page.
5.
Switch to Design view.
6.
In the Content control, change the text to Welcome to the Web site of .
7.
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]
8.
Set the Label control's ID property to CompanyName.
9.
In Solution Explorer, right-click Home.aspx, and then click View Code to open
the code editor.
10.
Inside the class definition, add the following code.
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 Home.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.
void
Page_Init(Object sender, EventArgs e)
{
this.CompanyName = "New Company
Name";
}
|
5.
Switch to the Home.aspx page, and then press CTRL+F5 to run it
again.
This time, the updated company name appears in
the page.
Notes
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).
·
You can reference controls on the master page by using the Master.FindControls method.

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="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.
Clear the BgColor
property.
The new master page will look and function like
Master1.master, but will have no 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.
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 Colorful.
4.
Double-click the button to create a handler for its Click event,
and then add the following highlighted code.
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 Plain.
7.
Double-click the Plain button to create a handler for its Click event, and then add the
following highlighted code.
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
1.
Switch to or open the About.aspx page.
![]() |
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.
|
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.
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 Plain link.
The page is redisplayed, this time merged with
Master2.master, which has no background color.
3.
Click the Colorful link.
The page is displayed using Master1.master
again.
Notes
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.
·
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.
·
You need to add the code from the Home.aspx page to every page where
you want to override the default master page.
ASP.NET Master Pages Overview
ASP.NET
master pages allow you to create a consistent layout for the pages in your
application. A single master page defines the look and feel and standard
behavior that you want for all of the pages (or a group of pages) in your
application. You can then create individual content pages that contain the
content you want to display. When users request the content pages, they merge
with the master page to produce output that combines the layout of the master
page with the content from the content page.

Master pages actually consist of two pieces, the
master page itself and one or more content pages.
Master Pages
A master page is an ASP.NET file with the
extension .master (for example, MySite.master) with a predefined layout that
can include static text, HTML elements, and server controls. The master page is
identified by a special @ Master directive that replaces the @ Page directive
that is used for ordinary .aspx pages. The directive looks like the following.
<%@ Master
Language="C#" %>
|
The @ Master
directive can contain most of the same directives that a @ Control directive
can contain. For example, the following master-page directive includes the name
of a code-behind file, and assigns a class name to the master page.
<%@ Master Language="C#"
CodeFile="MasterPage.master.cs" Inherits="MasterPage"
%>
|
In addition to the @ Master directive, the master page also contains all of
the top-level HTML elements for a page, such as html, head, and form. For example, on a master page you might use an HTML table for
the layout, an img element
for your company logo, static text for the copyright notice, and server
controls to create standard navigation for your site. You can use any HTML and
any ASP.NET elements as part of your master page.
Replaceable Content
Placeholders
In addition to static text and controls that will
appear on all pages, the master page also includes one or more
ContentPlaceHolder controls. These placeholder controls define regions where
replaceable content will appear. In turn, the replaceable content is defined in
content pages. After you have defined the ContentPlaceHolder controls, a master
page might look like the following.
C#
|
|
<%@ Master
Language="C#" %>
<!DOCTYPE html
PUBLIC "-//W3C//DTD XHTML
1.1//EN"
"http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html
xmlns="http://www.w3.org/1999/xhtml" >
<head
runat="server" >
<title>Master page
title</title>
</head>
<body>
<form id="form1"
runat="server">
<table>
<tr>
<td><asp:contentplaceholder id="Main"
runat="server" /></td>
<td><asp:contentplaceholder
id="Footer" runat="server" /></td>
</tr>
</table>
</form>
</body>
</html>
|
Content Pages
You define the content for the master page's
placeholder controls by creating individual content pages, which are ASP.NET
pages (.aspx files and, optionally, code-behind files) that are bound to a
specific master page. The binding is established in the content page's @ Page directive by including a MasterPageFile
attribute that points to the master page to be used. For example, a content
page might have the following @ Page
directive, which binds it to the Master1.master page.
<%@ Page
Language="C#"
MasterPageFile="~/MasterPages/Master1.master" Title="Content
Page"%>
|
In the content page, you create the content by
adding Content controls and mapping them to ContentPlaceHolder controls on the
master page. For example, the master page might have content placeholders
called Main and Footer. In the
content page, you can create two Content controls, one that is mapped to the
ContentPlaceHolder control Main and the other mapped to the ContentPlaceHolder control Footer, as
shown in the following figure.
Replacing placeholder
content

After creating Content controls, you add text
and controls to them. In a content page, anything that is not inside the
Content controls (except script blocks for server code) results in an error.
You can perform any tasks in a content page that you do in an ASP.NET page. For
example, you can generate content for a Content control using server controls
and database queries or other dynamic mechanisms.
A content page might look like the following.
[C#]
|
|
<% @ Page
Language="C#" MasterPageFile="~/Master.master"
Title="Content Page 1" %>
<asp:Content
ID="Content1" ContentPlaceHolderID="Main"
Runat="Server">
Main content.
</asp:Content>
<asp:Content
ID="Content2" ContentPlaceHolderID="Footer"
Runat="Server" >
Footer content.
</asp:content>
|
The @ Page
directive binds the content page to a specific master page, and it defines a
title for the page that will be merged into the master page. Note that the
content page contains no other markup outside of the Content controls. (The
master page must contain a head element
with the attribute runat="server" so that
the title setting can be merged at run time.)
You can create multiple master pages to define
different layouts for different parts of your site, and a different set of
content pages for each master page.

Master pages provide functionality that
developers have traditionally created by copying existing code, text, and
control elements repeatedly; using framesets; using include files for common
elements; using ASP.NET user controls; and so on. Advantages of master pages
include the following:
·
They allow you to centralize the common functionality of your
pages so that you can make updates in just one place.
·
They make it easy to create one set of controls and code and apply
the results to a set of pages. For example, you can use controls on the master
page to create a menu that applies to all pages.
·
They give you fine-grained control over the layout of the final
page by allowing you to control how the placeholder controls are rendered.
·
They provide an object model that allows you to customize the
master page from individual content pages.

At run time, master pages are handled in the
following sequence:
1.
Users request a page by typing the URL of the content page.
2.
When the page is fetched, the @ Page
directive is read. If the directive references a master page, the master page
is read as well. If this is the first time the pages have been requested, both
pages are compiled.
3.
The master page with the updated content is merged into the
control tree of the content page.
4.
The content of individual Content controls is merged into the
corresponding ContentPlaceHolder control in the master page.
5.
The resulting merged page is rendered to the browser.
The process is illustrated in the following
diagram.
Master pages at run time

From the user's perspective, the combined master
and content pages are a single, discrete page. The URL of the page is that of
the content page.
From a programming perspective, the two pages
act as separate containers for their respective controls. The content page acts
as a container for the master page. However, you can reference public
master-page members from code in the content page, as described in the next
section.
Note that the master page becomes a part of the
content page. In effect, the master page acts in much the same way a user
control acts — as a child of the content page and as a container within that
page. In this case, however, the master page is the container for all of the
server controls that are rendered to the browser. The control tree for a merged
master and content page looks something like this:
|
|
Page
Master Page
(Master page markup and controls)
ContentPlaceHolder
Content page markup and server
controls
(Master page markup and controls)
ContentPlaceHolder
Content page markup and server
controls
(Master page markup and controls)
|
This diagram is simplified; if the content page
does not have corresponding Content controls, the master page might also have
markup and controls in the ContentPlaceholder
controls.
In general, this structure has no effect on how
you construct your pages or program them. However, in some cases, if you set a
page-wide property on the master page, it can affect the behavior of the
content page, because the master page is the closest parent for the controls on
the page. For example, if you set the EnableViewState property on the content
page to true but set
the same property to false in the
master page, view state will effectively be disabled because the setting on the
master page will take priority.

When a content page is requested, its content is
merged with the master page, and the page runs in the context of the content
page. For example, if you get the CurrentExecutionFilePath property of the
HttpRequest object, whether in content page code or in master page code, the
path represents the location of the content page.
The master page and content page do not have to
be in the same folder. As long as the MasterPageFile attribute in the content
page's @ Page
directive resolves to a .master page, ASP.NET can merge the content and master
pages into a single rendered page.
Referencing External
Resources
Both the content page and master page can
contain controls and elements that reference external resources. For example,
both might contain image controls that reference image files, or they might
contain anchors that reference other pages.
The context for the merged content and master
pages is that of the content page. This can affect how you specify URLs for
resources, such as image files and target pages, in anchors.
Server Controls
In server controls on master pages, ASP.NET
dynamically modifies the URLs of properties that reference external resources.
For example, you might put an Image control on a master page and set its
ImageUrl property to be relative to the master page. At run time, ASP.NET will
modify the URL so that it resolves correctly in the context of the content
page.
ASP.NET can modify URLs in the following cases:
·
The URL is a property of an ASP.NET server control.
·
The property is marked internally in the control as being a URL.
(The property is marked with the attribute UrlPropertyAttribute.) In practical
terms, ASP.NET server control properties that are commonly used to reference external
resources are marked in this way.
Other Elements
ASP.NET cannot modify URLs on elements that are
not server controls. For example, if you use an img element on a master page and set its src attribute to a URL, ASP.NET will not modify the URL. In that
case, the URL will be resolved in the context of the content page and create
the URL accordingly.
In general, when working with elements on master
pages, it is recommended that you use a server control, even for elements that
do not require server code. For example, instead of using an img element, use an Image server control. That way, ASP.NET can
resolve URLs correctly and you can avoid maintenance issues that might arise if
you move the master or content page.
No comments:
Post a Comment