Click here to Skip to main content
Click here to Skip to main content
Go to top

Beginner's Tutorial on Master Pages in ASP.NET

, 21 Feb 2012
Rate this:
Please Sign up or sign in to vote.
Beginner's Tutorial on Master pages in ASP.NET

Introduction

This article is a beginner's tutorial on understanding Master pages and implementing master pages in ASP.NET.

Background

Coming from an application development background, when I started working on web development, the first thing I noticed was that all ASP.NET pages in our website required designing separately. Unlike Windows application, there is no way we can define common UI layout for ASP.NET pages. But this understanding of mine was short lived as I came to learn about Master pages in ASP.NET. Using master pages, I can actually create the common UI elements for all the web pages and create a consistent look and feel for my whole website. (Dreamweaver also provides a similar feature in the form of Templates).

Consistent UI is the key to good user interface. Before Master pages, the way we created consistent web pages was by using custom controls, CSS and JavaScript. With master pages, ASP.NET relieves the developer from the burden of creating the consistent web pages. Master pages not only provide the mechanism for creating consistent web pages, but also give us a centralized way of changing the UI elements that need to be changed across all the pages of the website.

To visualize the Master page - Content page relationship, let's look at the following picture:

understanding master pages images

Note: This image has been taken from www.asp.net.

We will be looking at how to use master pages in our website to provide consistent UI for our website.

Use of Master Pages

The master pages can be used to accomplish the following:

  • Creating a set of controls that are common across all the web pages and attaching them to all the web pages.
  • A centralized way to change the above created set of controls which will effectively change all the web pages.
  • Dynamically changing the common UI elements on master page from content pages based on user preferences.

Terminology

Let us look at the basic terminology that needs to be understood before jumping into master pages:

  • Masterpage: Gives us a way to create common set of UI elements that are required on multiple pages of our website.
  • ContentPage: The ASP.NET web page that will use master page to have the common UI elements displayed on rendering itself.
  • ContentPlaceHolder: A control that should be added on the MasterPage which will reserve the area for the content pages to render their contents.
  • ContentControl: A control which will be added on content pages to tell these pages that the contents inside this control will be rendered where the MasterPage's ContentPlaceHolder is located.

Creating a MasterPage

To create a master page, we need to:

  1. Go to "Add New Item".
  2. Select the MasterPage.
  3. understanding master pages images

  4. Let's say our master page is MasterPageOne.Master.
  5. We will now add a menu bar on this master page on top of the page. This Menu bar will be common to all the pages (since it is in Masterpage).
  6. Once we have menubar added, we can have content pages use the master page.
  7. Let's add few content pages like default.aspx, about.aspx, Contact.aspx. (We are simply creating some dummy pages with no functionality as we want to see the masterpage working, but these content pages can have any level of complex logic in them).
  8. When we add these content pages, we need to remember to select the option of "Use master Page".
  9. understanding master pages images

    and select the master page.

    understanding master pages images

Now let's look at the stuff that is important. When we look at the MasterPage, we will see that masterpage has a ContentPlaceHolder control. All the code that is common for the content pages is outside the ContentPlaceHolder control (in our case, a simple menubar).

<div align="center">
    <h1>My Test WebSite</h1>
    <asp:Menu ID="Menu1" runat="server" BackColor="#B5C7DE" DynamicHorizontalOffset="2"
        Font-Names="Verdana" Font-Size="0.8em" 
        ForeColor="#284E98" Orientation="Horizontal"
        StaticSubMenuIndent="10px">
        <StaticMenuItemStyle HorizontalPadding="5px" VerticalPadding="2px" />
        <DynamicHoverStyle BackColor="#284E98" ForeColor="White" />
        <DynamicMenuStyle BackColor="#B5C7DE" />
        <StaticSelectedStyle BackColor="#507CD1" />
        <DynamicSelectedStyle BackColor="#507CD1" />
        <DynamicMenuItemStyle HorizontalPadding="5px" VerticalPadding="2px" />
        <Items>
            <asp:MenuItem Text="HOME" Value="HOME" NavigateUrl="~/Default.aspx">
            </asp:MenuItem>
            <asp:MenuItem Text="ABOUT" Value="ABOUT" NavigateUrl="~/about.aspx">
            </asp:MenuItem>
            <asp:MenuItem Text="CONTACT" Value="CONTACT" NavigateUrl="~/contact.aspx">
            </asp:MenuItem>
        </Items>
        <StaticHoverStyle BackColor="#284E98" ForeColor="White" />
    </asp:Menu>

    <!--<span class="code-comment"> Here we have content place holder where all content pages 
    will render their controls   --></span>
    <asp:contentplaceholder id="ContentPlaceHolder1" runat="server">
    </asp:contentplaceholder>

</div>

understanding master pages images

Adding the ContentPages

If we look at our content pages, we will find a simple Content control added to each content page. This is the area where we will be adding our controls to be rendered along with the master page. (In our case, just simple strings.)

<asp:Content ID="Content1" ContentPlaceHolderID="ContentPlaceHolder1" Runat="Server">
<h2>This is a the CONTACT page.</h2>
</asp:Content>

Once we have all the master pages and content pages ready, we can test run our website.

understanding master pages images

So the common set of controls and behavior has now been added to all the content pages. We can have any number of controls and functionality on the master pages.

Changing the Master Page's Properties from Content Pages

There are times when we need to change some properties of master pages based on the current content page. These properties could be related to visible aspects of master page like UI elements or they could be of behavior aspects. The best way to do that is to have public properties in master pages that the individual content pages can use to customize the look/behavior of master page for that particular master page.

Let us, in our small test website, have a label in master page that will tell the user about the current page. Let's think of this label as breadcrumbs (just to illustrate there is no way, breadcrumbs should be created like this).

This label will display the string that is set by the Content page so we need to have a public property in the master page to accomplish that.

public string PageName
{
    get
    {
        return lblpageName.Text;
    }
    set
    {
        lblpageName.Text = value;
    }
}

Now we can use this property to set the PageName property of master page from content pages.

One important thing to mention here is that if we want to use this property from our content page, then we need to have a @Mastertype declaration in our content pages. This declaration will enable the content pages to use the public properties of Master Pages.

<%@ MasterType VirtualPath="~/MasterPageOne.master" %>

and from our content pages, we can simply set the property of the master page.

//default.aspx
protected void Page_Load(object sender, EventArgs e)
{
    this.Master.PageName = "/Default.aspx";
}

//about.aspx
protected void Page_Load(object sender, EventArgs e)
{
    this.Master.PageName = "/About.aspx";
}

//contact.aspx
protected void Page_Load(object sender, EventArgs e)
{
    this.Master.PageName = "/Contact.aspx";
}

and now if we run the website, we can see the label on master page showing the appropriate page name which is being set by the content page.

understanding master pages images

Changing the Master Page Dynamically

Now there are scenarios when we want the user to change the layout of the website. Since our website's layout is defined by the masterpage, to accomplish this we need the ability to change the master pages dynamically from the code.

So to do this, let us add one more master page to the website. This master page will have the menu vertically aligned on the left side unlike the first which has it on top.

understanding master pages images

Now to let the user change the MasterPage:

  • We need to have the option of changing the master page - let's have a new page change.aspx, we will place radio button on this page to be able to change master page for this page.
  • We need to save the current selected master page - let's save it in a session variable.
  • Change the master page on the fly - We need to do it in Page_PreInit of content Page Change.aspx.
//global.asax
void Session_Start(object sender, EventArgs e)
{
    // Code that runs when a new session is started
    Session["master"] = "~/MasterPageOne.master";
}

//change.aspx
protected void Page_Load(object sender, EventArgs e)
{
    if (IsPostBack == false)
    {
        RadioButtonList1.SelectedValue = Session["master"].ToString();
    }
}
protected void Button1_Click(object sender, EventArgs e)
{
    Session["master"] = RadioButtonList1.SelectedValue;
    //lets reload to see the change
    Response.Redirect("Change.aspx");
}

protected void Page_PreInit(object sender, EventArgs e)
{
    this.MasterPageFile = Session["master"].ToString();
}

Now when the user changes the Master Page from change.aspx, the masterpage for that page will be changed for that page for that session.

understanding master pages images

Points of Interest

Now let us try to sum up what we have seen so far by doing this small unrealistic example.

  • MasterPage gives a mechanism to create Consistent web pages.
  • We need to have ContentPlaceholder on each MasterPage and a Content control on each Content page.
  • Content pages can change the master page visibility and behavior by using the public property provided by MasterPage.
  • The MasterPage can be changed on the fly (programmatically) too.

There is also a possibility of having nested master pages if we carefully use MasterPage inside the ContentPlaceHolder of another master page thus exposing a new ContentPlaceHolder of nested MasterPage for content pages to use.

History

  • 21 Feb 2012: Understanding Masterpages in ASP.NET

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

Rahul Rajat Singh
Software Developer (Senior)
India India
I Started my Programming career with C++. Later got a chance to develop Windows Form applications using C#. Currently using C#, ASP.NET & ASP.NET MVC to create Information Systems, e-commerce/e-governance Portals and Data driven websites.

My interests involves Programming, Website development and Learning/Teaching subjects related to Computer Science/Information Systems. IMO, C# is the best programming language and I love working with C# and other Microsoft Technologies.
  • Microsoft Certified Technology Specialist (MCTS): Web Applications Development with Microsoft .NET Framework 4
  • Microsoft Certified Technology Specialist (MCTS): Accessing Data with Microsoft .NET Framework 4
  • Microsoft Certified Technology Specialist (MCTS): Windows Communication Foundation Development with Microsoft .NET Framework 4
 
If you like my articles, please visit my website for more: www.rahulrajatsingh.com[^]
Follow on   Twitter   Google+   LinkedIn

Comments and Discussions

 
QuestionNice Article Pinmemberheemanshubhalla19-Apr-14 7:58 
SuggestionCreating Master Pages in ASP.net Pinmembershine joseph30-Jan-14 1:14 
GeneralMy vote of 5 PinmemberSOMASUNDARAM SUBRAMANIAN16-Sep-13 21:56 
GeneralMy vote of 5 Pinmembersub.rohit6-Jul-13 0:04 
QuestionCreate and use ASP.NET Master Pages C# Pinmemberberkut200620-Jun-13 4:27 
QuestionMenu bar not centered PinmemberSheri Zdroik13-Feb-13 3:25 
GeneralMy vote of 5 Pinmembershashi426-Nov-12 2:51 
AnswerArticle of the Day on Microsoft's site PinmemberRahul Rajat Singh26-Oct-12 18:44 
GeneralMy vote of 5 PinmemberPrasyee10-Sep-12 22:26 
GeneralMy vote of 5 PinmemberImran D15-May-12 23:57 
GeneralMy vote of 5 PinmemberP.Salini11-May-12 20:13 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Mobile
Web03 | 2.8.140926.1 | Last Updated 21 Feb 2012
Article Copyright 2012 by Rahul Rajat Singh
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid