- In the first approach, you expose the controls in the master page using public properties. This means you need to create one property for each control that should be made available to the content pages.
- In the second approach, you get a reference to the master page controls in a standard wayusing the FindControl methodwhich is available because the Master class derives from System.Web.UI.Page class.
The following code shows an example that accesses a control in the master page from a content page.
<%@ master language="C#" %>
<html>
<head id="Head1" runat="server">
<title>Master Page</title>
</head>
<body>
<form id="Form1" runat="server">
<table id="header" style="WIDTH: 100%; HEIGHT:
80px" cellspacing="1" cellpadding="1" border="1">
<tr>
<td width="100%" style="TEXT-
ALIGN: center">
<asp:label runat="server" id="Header">
This is the default header in the Master
Page</asp:label>
</td>
</tr>
</table>
<b/>
<table id="leftNav" style="WIDTH: 108px;
HEIGHT: 100%" cellspacing="1" cellpadding="1"
border="1">
<tr>
<td style="WIDTH: 100px"> Left
Navigation
</td>
</tr>
</table>
<table id="mainBody" style="LEFT: 120px; VERTICAL-
ALIGN: top; WIDTH: 848px; POSITION: absolute; TOP:
94px; HEIGHT: 100%" border="1">
<tr>
<td width="100%"
style="VERTICAL-ALIGN: top">
<asp:contentplaceholder
id="middleContent"
runat="Server">
</asp:contentplaceholder>
</td>
</tr>
</table>
</form>
</body>
</html>
The preceding code is very similar to the code in
Listing 1; however this version contains a server side control named "Header" in the header section. The following code shows how to access the Header control from a content page.
<%@ page language="C#" master="~/ExposeHeader.master" %>
<script runat="server">
void Page_Load(object sender, System.EventArgs e)
{
Label headerLabel = (Label)
Master.FindControl("Header");
headerLabel.Text = "This label
content is set through the
Page_Load event of the child
page";
}
</script>
<asp:content id="Content1"
contentplaceholderid="middleContent"
runat="server">
This content is generated from the content page.
</asp:content>
The preceding code starts by specifying the name of the master file to use. The
Page_Load event invokes the
FindControl method of the Master class, passing it the name of the master page control to find. The code casts the returned value to a Label control and then sets its Text value.
Apart from accessing all the controls of the master page, you can also access the public properties and methods exposed by the master page from the content pages using an early-bound approach. This early-bound approach not only increases the performance but also provides compile time type-checking, resulting in increased developer productivity.