Partilhar via


Inside ASP.NET Master Pages

Inside ASP.NET Master Pages

Introduction

Master pages are templates for ASP.NET pages. It helps you to create consistence appearance for your web site with minimum code effort. The great thing about master pages that it's live templates, you can change them from within the content pages. it’s not only for visual consistency but it can also act as global function library. Any function declared in the master page is viewable in any content pages.

Create master page

Creating master page is very simple. From Visual Studio solution explorer:

  • Right click on project name and choose “Add New Item”.
  • From the templates’ window, choose “Master Page”.
  • Choose the language of it and whether or not it has code behind page.


 


Adding controls to Master page.

Master pages are much like normal aspx pages but it doesn’t have the @Page directive. Instead it contains this directive

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

Also the extension of the master pages is “.Master” and make sure that you don’t change this extension because this prevents the pages from being browsed by browsers directly. I’ll explain this later in this article.

Now you are free to add any controls or Code to your master page. You can add navigation controls such as TreeView or SiteMapPath controls, you can add a header and footer or any parts that you think that it will be consistent along with your site.

You should note that by default when you create master page it contains only one control. It’s the ContentPlaceHolder. It’s used by master pages to determine the places where you can add content through content pages. You can have one or more ContentPlaceHolder. The declaration of it should be something like this.

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

Note:
All code snippet in this article in C#, For full VB.NET code, please refer to the attached source code.

 

Creating Content pages

To create Content page from Visual Studio, in the solution explorer

  • Right click on the project name then choose “Add New Item”

  • From the template window Choose WebForm and check the checkbox “Select Master Page” This will give you the option to select which master page you want to choose.


    When you open the web from in the Visual Studio designer you notice that the controls of the master page appear but you can’t edit it.
    When you view the source of the content page, it looks like this

 <%@ Page Language="C#" MasterPageFile="~/MasterPages/myMasterPage.master" 
AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<asp:Content ID="Content1" ContentPlaceHolderID="ContentPlaceHolder1" Runat="Server">
     
</asp:Content>

The link between the content page and master page is in the attribute MasterPageFile. The content page doesn’t have any <html>, <body> or <form> tags because they already in the master page.
Content page can only have Content controls associated with ContentPlaceHolder control. And any controls/literals should be placed only in this Content control.

Now try to add anything to the content page and browse it. You will see the content of two pages together.

Note
Can I browse master pages directly?
No, you can’t because .master extension is associated with System.Web.HttpForbiddenHandler So it always gives you the error “This type of page is not served” That why you shouldn’t change the extension of the master file.
 

Master-Content relation is not inheritance.

  • After having quick overview about master pages, it’s time to dig through it internally. It might seem that the relation between Master and Content page is “Inheritance” like what happens in windows forms’ visual inheritance. But in fact it’s far from the truth.

    Master pages are actually user controls. When you see the code file of your master page, you will find that it inherits the class MasterPage which in turn inherits UserControl ,

The complete family tree in the image below

What actually happens when the user requests a web form in ASP.NET 2.0 is:

  • The ASP.NET runtime checks to see whether the page has a master page
  • If the page associated with master page, the runtime first initialize the master page
  • The runtime merge the content of the master page with the content of content page. That happens in the init event of the web form, see performPreInit() method of the System.Web.UI.Page class.
 private void PerformPreInit()

{

this.OnPreInit(EventArgs.Empty);

this.InitializeThemes();

this.ApplyMasterPage();
this._preInitWorkComplete = true;

}

 

  • Runtime sends the output of merged pages to the client.



How controls arranged in the output

The master page is working as a container for the controls inside it. If you examined the trace output of this page, you will find something like

Ctl00 is the id of the master page and all controls inside the master page begin with ctl00$<control name>
One of the implications for this is if you tried to get any control in the master page from the content page using code like this

 TreeView tv=(TreeView) this.FindControl(“TreeView1”);

It will not succeed.

 

How to interact with master page controls from content page

The next question is “How to change something in master page from content page?”
To do that, the product team changed the Page class to add new property in it called Master. This is the signature of it.
 

 public MasterPage Master

{

get

{}

}

It returns an instance of the MasterPage class. To access controls inside the master page, there are two methods:
 

1) Using public Properties/Methods
If you noticed, the content page doesn’t have <header> and <title> tag. So if we want to change the title of the content page –and this is mandatory- we need to access the <title> tag.
First we need to change the title tag so it can be accessible from the code page. Simple we need to add id and runat attributes as following

 <title id="pageTitle" runat="server"></title>

Then, in the master page add this property

 public string mainTitle

{

set
{pageTitle.Text = value;}

}

And finally on the content page, we add this snippet on the load event.

 myMasterPage myMaster = (myMasterPage)this.Master;
myMaster.mainTitle = "Playing with master pages :)";

2) Using FindControl method
Let’s say that I have a ListBox control on the master page called listBox1. And I want to access it.
We don’t need to add any code in the master page. Just in the content page add

 myMasterPage myMaster = (myMasterPage)this.Master;
ListBox masterListBox = myMaster.FindControl("ListBox1") as ListBox;
if (masterListBox != null)
masterListBox.Items.Add("accessed from content page");

Note:
Because the Master property returns a reference of type MasterPage, we need to cast it to myMasterPage class. We can avoid this by adding the @MasterType directive in the content page as following

 <%@ MasterType TypeName="myMasterPage" %>

Then we can change the line of getting a reference to the master page to be

 myMasterPage myMaster =this.Master;

 

Calling functions from the master page.

We can use the master pages not only as a visual template but we can also use it as function library where we can add the most common, UI-related functions.

But take care to not add a lot of code because it will be loaded with each and every page in your web site.

Let’s say that we have a function called masterFunction as following

 public string MasterFunction()

{
return "this is returned from master page";

}

We can simply call it with this code snippet.

 //make sure that you added the MasterType directive.
myMasterPage myMaster =this.Master; 
lblTest.Text = myMaster.MasterFunction();


When my code is executed?

That’s very important question to ask, when you put code in the master and content pages’ load event, which one will be executed first. Well it’s in this order
Master – initialize
Content- initialize
Content- load
Master – load
Content- render
Master- render

I did a nice code sample that demonstrates the event order. Take a look at the code attached with this article.

 

Master pages don’t support themes

Master page doesn’t support themes simply because the System.Web.UI.Page.PerformPreInit() method initialize the theme for any web form then apply the master page. That’s why master pages throw exception if you tried to apply themes on them. See code below

  void PerformPreInit()
{
this.OnPreInit(EventArgs.Empty);
this.InitializeThemes();
this.ApplyMasterPage();
this._preInitWorkComplete = true;
}

But if the content page has a theme, it will be applied on the whole output later after merging the master and content page.

Take care of URLs

If we have image control on the master page (or any control that reference URLs). And we have a relative URL (something like images/myImage.gif). It’s relative to the place of the master page in the web site but when the master page is merged in the content of the content page, what will be the situation?
Don’t worry about that, ASP.NET runtime will take care of converting any URLs to the appropriate ones.

But take care of non-server-controls tags like <img> tag. ASP.NET runtime has not control over HTML tags so you need to avoid relative URLs with any HTML tags in master page. For example, you can add a URL to image using https://mysite.com/myfolder/image.gif.


Adding Master page to the whole site at once

If you have a single master page that you wish to add to all your web forms without specifying the MasterPageFile attribute on every page you can add this on the web.config

 <pages masterPageFile="mySite.master" />


Nested Master Page

 

Master pages can be nested. You can use this feature to distribute your master pages design among more than one master page.
The only defect using this strategy is that Visual Studio doesn’t support nested master pages. So you have to work without Visual Studio designer.

Note:
Any master page that has another master page should be treated like the content page so it can not have anything outside the Content control.
So the only page that will have <head> and <body> tags is the topmost master page.

Let’s say that you have a page called nestedMasters.aspx which has a master page called childMaster.master and this master page has another master page called topMaster.master. The code of the topMaster.master would be like this

 <%@ Master Language="C#" AutoEventWireup="true" CodeFile="topMaster.master.cs" 
Inherits="topMaster" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "https://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="https://www.w3.org/1999/xhtml" >
<head runat="server">
<title id=pageTitle runat=server>Untitled Page</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<table width="100%">
<tr width=100%>
<td width=100% bgcolor="#99ff99">This is the parent master page<br />
<asp:Label ID="label1" runat="server" Text="Label" Width="351px"></asp:Label>
</td>
</tr>
<tr width=100%>
<td width=100%><asp:contentplaceholder id="ContentPlaceHolder1" runat="server">
</asp:contentplaceholder></td>
</tr>
</table>

</div>
</form>
</body>
</html>

And the childMaster.master code is:

 <%@ Master Language="C#" AutoEventWireup="true" CodeFile="childMaster.master.cs" 
Inherits="childMaster" MasterPageFile="~/MasterPages/topMaster.master" %>
<asp:Content ID=content1 runat=server ContentPlaceHolderID=ContentPlaceHolder1>
<table width=100%>
<tr width=100%>
<td width=100% bgcolor="#00ccff"> This is child master page<br />
<asp:Label ID=label1 runat=server Text=Label />
</td>
</tr>
<tr width=100%>
<td width=100%><asp:ContentPlaceHolder ID=contentPlaceHoder1 runat=server EnableViewState=true></asp:ContentPlaceHolder></td>
</tr>
</table>
</asp:Content>

And the nestedMasters.aspx should be like this:

 <%@ Page Language="C#" MasterPageFile="~/MasterPages/childMaster.master" AutoEventWireup="true" CodeFile="nestedMasters.aspx.cs" Inherits="nestedMasters" 
Title="Untitled Page" %>
<asp:Content ID="Content1" ContentPlaceHolderID="contentPlaceHoder1" Runat="Server">This is content page
</asp:Content>

Creating nested master pages is very simple. But when it comes to interaction between content page and master page, it needs us to pay attentions to some issues.

Arrangement of controls in the output page is very important to know if you want to deal with nested master pages. Take a look at this image of page tracing.

Note that the content page is the container for the childMaster and the childMaster is a container for topMaster and all the controls declared in childMaster and topMaster are inside the topMaster.
To differentiate between the controls that are in childMaster and topMaster, all childMaster controls are found in the ContentPlaceHolder1 control in topMaster.

This will lead us to another question, What about the interaction between the content page and the master pages?

The only visible class to the content page is the direct master page. The content page can’t create a reference of the type of any master page other than its direct master page. So you can’t use them directly from content page.
To overcome this I found two ways to do this.

Using Properties/Methods
You can use properties or methods only in the childMaster page (the direct master page to the content page). And the properties or methods in the childMaster change the controls in the topMaster.

Let’s say I want to change two controls

  • Label on the childMaster master page
  • The HTMLTitle on the topMaster master page
     

In the childMaster, add these two methods

 public void changeLocalControl(string controlName, string newValue)

{
if (controlName == "label1")
        {
label1.Text = newValue;
    }

}
 
 
public void changeMasterControl(string controlName, string newValue)

{
topMaster myMaster = (topMaster)this.Master;
if (controlName == "pageTitle")
        {
HtmlTitle title = myMaster.FindControl("pageTitle") as HtmlTitle;
 if(title !=null)
 title.Text=newValue;

}

}

In changeLocaControl method, you simply change a control that is in the same page you are in. Just reference the control by its ID as usual.

In changeMasterControl method, you declare a reference to the topMaster class and assign to it the result of the Master property of the childMaster class. Then using FindControl method, get a reference to the HTMLTitle object in the topMaster class then change it.
 

Using FindControl from content page directly
If you are in a hurry and you don’t want to bother yourself with writing properties or methods in the childMaster page, you can directly access any control in the topMaster page by the following.

According to the trace output earlier, all controls on childMaster and topMaster reside in the topMaster page.

To get a control in the topMaster page use the Master property of the childMaster to get a reference of the topMaster class then use FindControl to get the control, see the code snippet below.

 Label lbl = myChildMaster.Master.FindControl("label1") as Label;
lbl.Text = "testing";

To get a control in the childMaster page, it’s a bit tricky but keep in mind two things.
1) All controls are in the topmost master page
2) Controls that belongs to children master pages are in the appropriate ContentPlaceHolder control in the topmost master page.

Now take a look at the trace output and check this code snippet below.

 Button btn = myChildMaster.Master.FindControl("ContentPlaceHolder1").FindControl("button1") as Button;
btn.Text = "by the content page";

In this code, I get a reference to the topMaster page using the Master property of the childMaster page then I dig through the controls hierarchy to reach the button1 through the ContentPlaceHolder1 control.

I hope I could shed a light on Master Pages and I’m waiting your feedback :)

Comments

  • Anonymous
    August 18, 2005
    Mohamed - Inside ASP.NET Master Pages

    Mohamed gives a VERY detailed overview of Master Pages.

    Chris...

  • Anonymous
    November 15, 2005
    What if you want one master page that 30 web applications are going to utilize? Where do you place the master page? Do you have to copy it to each web project?

  • Anonymous
    February 25, 2006
    Hi Jason,
      Yes, you have to copy the master page accross all your projects.

    //Mohamed

  • Anonymous
    September 17, 2006
    Is it possible to determine the filename of the child page from the Page_Load() event in Site.Master? I'm having a mental block and just can't figure this one out.

  • Anonymous
    September 17, 2006
    My brain freeze is over - I can simply check "Request.FilePath"

  • Anonymous
    October 16, 2006
    Tony, Don't slam people. Be nice.

  • Anonymous
    December 03, 2006
    Hi... I have a master page which has a place holder I am adding a image control to that place holder programatically in page load of master page In my webform which uses this master, i want to change the url? How to do that?

  • Anonymous
    December 19, 2006
    Hi I would like to how can i access the Client side code inside the server side code of a master page. Thanks

  • Anonymous
    January 23, 2007
    i need a help releting  to master page. whn we r using master page in our project thn its not necessary that all page should same size. whn we cteared master page thn its size is fixed n wh we add next page having master page if lenth of next page is greater than or it having a lot info than size provided by master page thn footer of master page is overlapped. thn what i would do in such condition.

  • Anonymous
    March 05, 2007
    The comment has been removed

  • Anonymous
    March 07, 2007
    How do I access an control that is created within a child page from client javascript. Specifically, I am woorking with a textarea... The whole "ctl00$ContentPlaceHolder1$" prefix makes it impossible (for me) to reference the control from javascript at runtime... Some pertinent Code:           strUniqueScriptName = "resetText";            System.Text.StringBuilder sb2 = new System.Text.StringBuilder();            sb2.Append("<script language="JavaScript">");            sb2.Append("function resetText() { ");            sb2.Append("if (document.form1.");            sb2.Append(sControlName);            sb2.Append(".value.length < 1)");            sb2.Append("{");            sb2.Append("document.form1.");            sb2.Append(sControlName);            sb2.Append(".value = 'Comments (355 characters maximum)'");            sb2.Append("}");            sb2.Append("}");            sb2.Append("</script>");            if (!Page.ClientScript.IsClientScriptBlockRegistered(strUniqueScriptName))            {                Page.ClientScript.RegisterClientScriptBlock(this.GetType(), strUniqueScriptName, sb2.ToString()); } Thanks, Spencer

  • Anonymous
    March 07, 2007
    OK, I figured this out: I am doing this with a User Control. I reference the control in the Child page: <%@ Register TagPrefix="spr" TagName="SPRCommentBox" Src="SPRCommentBox.ascx" %> Then use the control multiple times in the Child page: <spr:SPRCommentBox runat=server ID="SPRComment1" /> Each instance of the control on the Child page gets it uniquely naed JavaScript function. In the User Control (ascx) I add a TextBox:        <asp:TextBox ID="SPRCommentBox1" runat="server" Height="145px"            Style="z-index: 100; left: 0px; position: absolute; top: 0px"            Width="564px"              MaxLength="10"              TextMode="MultiLine"            >Comments (355 characters maximum)         </asp:TextBox> In Page_Load: SendScripts(SPRCommentBox1.ClientID, Page.Form.ClientID.ToString());            SPRCommentBox1.Attributes.Add("onfocus", SPRCommentBox1.ClientID + "_clearText()"); Then as a routine: private void SendScripts(string sControlName, string sForm)        {            string strUniqueScriptName = sControlName + "_clearText";            System.Text.StringBuilder sb = new System.Text.StringBuilder();            sb.Append("<script language="JavaScript">");            sb.Append("function ");            sb.Append(strUniqueScriptName);            sb.Append("() { ");            sb.Append("document.");            sb.Append(sForm);            sb.Append(".");            sb.Append(sControlName);            sb.Append(".value = document.");            sb.Append(sForm);            sb.Append(".");            sb.Append(sControlName);            sb.Append(".value.replace(/^\s*|\s*$/g,'');");  //trim            sb.Append("if (document.");            sb.Append(sForm);            sb.Append(".");            sb.Append(sControlName);            sb.Append(".value == 'Comments (355 characters maximum)')");            sb.Append("{");            sb.Append("document.");            sb.Append(sForm);            sb.Append(".");            sb.Append(sControlName);            sb.Append(".value = '';");            sb.Append("}");            sb.Append("}");            sb.Append("</script>");            if (!Page.ClientScript.IsClientScriptBlockRegistered(strUniqueScriptName))            {                Page.ClientScript.RegisterClientScriptBlock(this.GetType(), strUniqueScriptName, sb.ToString());            } } I hope this helps someone else avoid the myriad of problems I had getting this to work!

  • Anonymous
    March 14, 2007
    I got a feedback for the Master Pages post asking about mixing master pages with cross post. Here's the

  • Anonymous
    April 19, 2007
    Thanks a lot especially to you and Spencer Sullivan. Genious explanations. I really have problems with refering controls (e.g. dropdownlist)inside Gridview or Formview using Javascript DOM. Yet to experiment but hope could resolve it. Thanks again

  • Anonymous
    May 03, 2007
    i have created one website with master and content page.when i tried to apply themes it is not working.but same theme code is working in a normal webpage plz help

  • Anonymous
    June 03, 2007
    hai, i have one problem with master pages, Server controls are unknow  if used in Master/Content pages   the server controls are showing in red underlined in a contentholder page. please give a solution for this thanks Subramanyam

  • Anonymous
    July 24, 2007
    I had built a functional aspx with code behind page.  I tried to use a master page and contentplace holder with this code and it gives me errors like "Gridview1" not defined.  When it works fine without Mater pages and content place holders.  Do I HAVE to build a control out of the pages to use it in the content place holder? Thanks, Rusty

  • Anonymous
    July 09, 2008
    Hi: I have a child form. And obviously, that child form will not contain any <form> tag. And because of that my javascipt is braking where it is trying to get like: document.forms[0].elements[idname].value Here idname is my control name [txtname].