Click here to Skip to main content
Click here to Skip to main content

ASP.NET 2.0 Master Pages

, 28 May 2005
Rate this:
Please Sign up or sign in to vote.
Master Pages is a great addition to ASP.NET 2.0. It's so important for templatizing your website, you will learn how to create master pages and content pages, with one simple example and some useful tips.

Introduction

In ASP.NET 1.1, to give your application a coherent style you were using user controls to make one footer and one header, maybe you make one menu, then you drop those controls into each and every new page you add to your application, it's somehow a good way to make a consistent maintainable UI. Master Pages is an easier solution!

What are Master Pages ?

Master pages let you make a consistent layout for your application, you can make one master page that holds the layout/look & feel and common functionality of your whole application and upon this master page, you can build all the other pages, we call these pages Content Pages. So simply you can build your master page and then build content pages, and while creating the content pages you bind them to the master page you have created before, those two pages are merged at runtime to give you the rendered page.

Master Pages and ContentPlaceHolders

The master page has the extension .master and it's actually an aspx page but with the directive <%@ Master Language="C#"%>, instead of the standard page directive, almost the attributes of the Master directive are the same as that of the page, you can add any kind of controls the same as you design aspx pages, and it's advisable to use the menu control at your master page ( menu is one of the most nice added controls to ASP.NET 2.0). Every MasterPage should include at least one ContentPlaceHolder, this control is a placeholder for the content that will be merged at runtime, noting that the content page is just an aspx standard page but you should supply the attribute MasterPageFile to the page directive to bind the content page to the master page, for example:

<%@ Page Language="C#" MasterPageFile="~/MasterPages/SiteLayout.master"%>

Again, you can design your content page just like any other aspx page adding any static text and server controls.

Content Server Control

Inside the content pages you will find one Content server control added by default, actually when you add controls you add them to the content server control. For example,

<asp:Content ID="Content1" ContentPlaceHolderID="ContentPlaceHolder1" 
            Runat="Server">

The attribute ContentPlaceHolderID is very important as it decides what content will be bound to which ContentPlaceHolder on the master page, this is a very nice way to decide the location of where the contents will be displayed; so this way you can have multiple content on one content page and also multiple ContentPlaceHolders on the master page.

Note: The content pages don't include the common tags as <Body>, <Head>,etc. Remember that, that was the same with user controls, as after merging, there should be only one Body and Head tags.

Programmable Master Pages

Master Pages are programmable. You can make one property to the master page and it will be visible to all the content pages, for example you can get one string like last build or last update from web.config file and provide it as a public property to all the content pages.

Maintainable Master Pages

The best thing about master pages is maintainability as you can now update one master page and this will update all your application pages that refer this master page.

Creating Master Page

  • Open Visual Studio 2005.
  • Create new ASP.NET Web site, enter name as MasterPagesApp.
  • Select Location as File System, and enter the path as D:\WhidbeyWebSites\MasterPagesApp( or any other path ).
  • Select the Language you are more comfortable with, for this we will use C#.
  • After creating the new Web Site, you will find a page created for you named Default.aspx.
  • Delete this page and right click the application from solution explorer. Select Add New Item, select Master Page from installed Visual Studio templates and name it MainLayout, and check the Place code in separate file checkbox; this will create you a code-behind in the language you select, we work here using C#.

  • The MainLayOut.master will be open in Source view. You will find this master page directive at the beginning:

    <%@ Master AutoEventWireup="true" CodeFile="MainLayOut.master.cs" 
        Inherits="MainLayOut" Language="C#" >

    As you see, the attributes of the Master directive is common to the ones of the Page directive, and they are self-descriptive; CodeFile is the path of the code behind file. It can be VB or C#, note that in one Web Site you can mix between both languages. Inherits decides the class within the code file to be used. Language is the language of the code behind file. AutoEventWireup is so important; for any page there is an automatic way to bind the events to methods in the same aspx file or in code behind, if this attribute is true ( default value is true so if it's not mentioned, it will be true ). Page events are automatically bound to methods that are using naming convention as Page_event, for example Page_Load, Page_Init, and Page_PreInit (this is the event fired before creating the controls of the page). This has one disadvantage that the standard events of the page should adhere to this naming convention, but if you set it to false, it will give you more flexibility to use any names for the event handlers, here we should remember the importance of Handles keyword in VB.NET.

    You should also examine the following section:

    <asp:contentplaceholder id="ContentPlaceHolder1" 
           runat="server"></asp:contentplaceholder>

    This server control is the most important for the master pages as this is the zone in which the content pages will be rendered.

  • Switch to the Design of the master page, you will get the ContentPlaceHolder1 shown, now you can design the master page just as any aspx page, so for this practice we'll do a simple master page.
  • From Layout menu select Insert Table, Select Template option, then select Header , footer and side, then drag the ContentPlaceHolder1 control into the right middle cell of the table you have just added.
  • Add one label into the left middle cell, and the logo of CodeProject to the upper cell of the table, you should have the same as in the following figure

  • Note: You should make all the paths in the master page relative to one folder because the image path will be relative to the rendered content page not for the master page. It's advisable to create one images folder to hold all your images, for example the logo of CodeProject image path is : ./images/codeprojectlogo.JPG. When the content page renders, the path will be evaluated to http://localhost:4843/MasterPagesApp/images/codeprojectlogo.JPG.
  • Double click anywhere at the master page. This will open the code behind and will add the Page_Load event handler. You can write the following code:

    Label1.Text = "The Time of Server is: " + DateTime.Now.TimeOfDay;

    This will show the time of the server at the label.

Creating Content Page

You should know that the content page is just one aspx page but you bind this page to one master page while you are creating it. To do this, right click your web application from solution explorer and select Add New Item, select Web Form from the installed templates and check Select Maser Page, enter the name of the new page as myContentPage.aspx as in the following figure:

Because you have checked the Select Master Page box, you will get the following dialog to select one master page, this will bind the new aspx page to the selected master page as shown in the following figure:

The page you have just added will open in source view and you will find one entry. Add the MasterPageFile attribute set to the value of the master page file you have selected before. This should be assigned the value ~/MainLayOut.master. You will also find one Content server control added by default and the attribute ContentPlaceHolderID assigned to ContentPlaceHolder1. This is the default value which refers to the ContentPlaceHolder control at the master page and if you have renamed this control at the master page, you should change it now to the correct ID. This sets the zone in which this content page will be shown as we said before.

Switch to the design view of myContentPage.aspx. You will get the following figure which shows all the master page contents added by all the contents of the master page is dim because they are not editable, only the Content1 will be enabled if you click the white area, and you can now add any controls just as you do for any aspx page.

Double click the white area of Content1, you will get the event handler of Page_Load, add the following line:

Label1.Text = this.MasterPageFile;

This will show the path of the Master Page file into the label. Actually you can get a reference to the Master Page from a content page by using the Master property which refers to the page's master page, furthermore you can refer to any control on the master page by using this.Master.FindControl(string id), this method takes the Id of the control on the master page and returns Control object, so you should cast to the data type of the control.

Saving Master Page path in web.config

There is one technique by which you can make all the pages comprising your web application as content pages and you can bind all the pages to one master page, this master page that will be a template to your entire application. It's advisable to save the path of this master page into web.config, you can do that using the following:

<configuration> 
  <pages masterpagefile="~/sitetemplate.master"> 
</configuration> 

If you specify a MasterPageFile for your page, it will override your web.config value but the importance of the value of web.config is that it guarantees that all the pages added to your application are bound to this master page file, so if you have more than one master page, you can just change the web.config value, and this will update the whole application pages with no need to recompile. Indeed this technique was a trend at ASP.NET 1.x, as some developers were making all the pages as user controls and pass the id of the user control at the required page URL.

Conclusion

Master Pages are a great addition to ASP.NET 2.0, it's a good way to templatize your application. As we've seen you can change the master page from web.config, and you can access the master page from child content pages by using this Master, thanks to Master Pages!

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here

Share

About the Author

Kareem Shaker
Architect
United Arab Emirates United Arab Emirates
Kareem Shaker is a .NET Architect , He's been working with VC++ and VB since version 4.0 ; Kareem has been working on design and development of many business applications , And he's now spending most of his time working with .NET Framework 1.x and 2.0 using both VB.NET and C# , Kareem has been giving some technical sessions targeted to .NET technologies, One of the technolgoies that I have passion to is EAI, I spend most of my times working on BizTalk Server 2006, I like to share knowledge and to interact with geeks around, Blogging is one of my hobbies, my blog is http://CairoCafe.Blogspot.com

Comments and Discussions

 
GeneralMy vote of 5 Pinmemberali_0569831-Oct-12 17:07 
GeneralMy vote of 3 PinmemberMember 89494501-Jun-12 1:24 
GeneralThanks alot PinmemberAlireza_13626-May-12 7:18 
SuggestionMaster pages, style sheets and themes PinmemberNotAndrewTurvil1-May-12 1:25 
GeneralMy vote of 4 PinmemberMember 287445731-May-11 18:30 
GeneralMy vote of 4 Pinmembernikumbh nilesh28-Aug-10 22:16 
GeneralMy vote of 4 Pinmemberjon_8017-Aug-10 7:00 
GeneralQuite nice and useful -- but loopholes regarding javascript Pinmemberjaivardhan joshi25-Dec-09 21:04 
GeneralMaster Pages in ASP.NET 3.5 Pinmemberziek7-Sep-09 17:01 
GeneralNice and Simple PinmemberVuyiswa Maseko28-Aug-08 1:59 
GeneralMaster page error Pinmemberadriaanj14-Aug-08 4:07 
QuestionFull page refreshes... PinmemberSatyam Kumar3-Dec-07 18:04 
GeneralNested Master Pages PinmemberMichael Davey 126-Nov-07 18:18 
GeneralRe: Nested Master Pages PinmemberKareem Shaker26-Nov-07 21:56 
Generalmasterpagefile and dialog buttons for new page Pinmember1of37-Nov-07 13:05 
GeneralCorrection for pages element in Web.Config Pinmembermclai26-Oct-07 11:00 
GeneralVery Good Article PinmemberUsualDosage5-Jul-07 3:20 
GeneralRe: Very Good Article PinmemberKareem Shaker5-Jul-07 3:25 
GeneralRe: Very Good Article Pinmemberchaudharimehul28-Sep-07 1:43 
QuestionHow about a web service call from a content page Pinmemberfpatton27-May-07 9:29 
AnswerRe: How about a web service call from a content page PinmemberKareem Shaker28-May-07 2:05 
Generalusing CSS Pinmemberblumenhause16-May-07 3:24 
Questionerror in source Pinmemberveerbala18-Apr-07 3:26 
Questionmaster pages Pinmemberaxzsaxzs7-Mar-07 1:46 
GeneralAyuda urgente Pinmemberhernanr24-Jan-07 3:51 
Questioncan we apply AJAX.net in master page [modified] Pinmemberi.zone12-Dec-06 17:47 
AnswerRe: can we apply AJAX.net in master page PinmemberKareem Shaker20-Dec-06 0:48 
GeneralRe: can we apply AJAX.net in master page Pinmemberssaud11-Jan-07 0:13 
GeneralRe: can we apply AJAX.net in master page Pinmemberfr33l0ad3r1-Aug-07 15:04 
QuestionImage not displayed in master page Pinmemberricredor21-Aug-06 22:21 
AnswerRe: Image not displayed in master page PinmemberKareem Shaker21-Aug-06 22:50 
GeneralRe: Image not displayed in master page Pinmemberricredor21-Aug-06 23:22 
GeneralRe: Image not displayed in master page PinmemberKareem Shaker21-Aug-06 23:31 
GeneralRe: Image not displayed in master page Pinmemberricredor22-Aug-06 0:02 
GeneralRe: Image not displayed in master page PinmemberKareem Shaker22-Aug-06 1:33 
AnswerRe: Image not displayed in master page PinmemberMario_F10-Nov-06 21:33 
GeneralRe: Image not displayed in master page PinmemberMario_F10-Nov-06 21:36 
GeneralMaking header and footer visible = false Pinmemberpadvit10-May-06 0:10 
GeneralRe: Making header and footer visible = false Pinmemberssaud11-Jan-07 0:17 
GeneralAccess the Control from the content page PinmemberRamkumar Dotnet5-Mar-06 20:27 
GeneralRe: Access the Control from the content page Pinmemberveerumca16-Jul-06 21:39 
GeneralRe: Access the Control from the content page Pinmemberdarkrd3-Nov-06 18:27 
Generalhai, Pinmembersivamohanreddy28-Jul-05 8:26 
GeneralRe: hai, Pinmembersammy19711-Jan-06 21:41 

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 | Terms of Use | Mobile
Web01 | 2.8.1411023.1 | Last Updated 28 May 2005
Article Copyright 2005 by Kareem Shaker
Everything else Copyright © CodeProject, 1999-2014
Layout: fixed | fluid