We all know that MasterPages are generally used for uniform look and feel in Web Applications. In this blog post I want to show some interesting facts about MasterPages in a Q&A format. So lets get started.
-
Can a MasterPage and a ContentPage be developed in 2 different languages? i.e. Suppose can I have a master page developed in VB.NET and a content page in C#.NET?
Ans: Yes this is perfectly possible. Because the @Master directive doesn’t override the attributes set at the @Page directive level.
-
How is the relation established between a Master Page and a content page at runtime?
Ans : The link is established through the ContentPlaceHolderID. Say for example I have a MasterPage called Default.Master , there is a section for ContentPlaceHolders with ID=”PageContent”. Now say for example I create a .aspx page and set the MasterPage as Default.Master, the ContentPlaceholderID in the Content Page will be “PageContent”. The following diagram details the same.
MasterPage Source
<%@
Master
Language=”C#” AutoEventWireup=”true” CodeFile=”MasterPage.master.cs” Inherits=”MasterPage”
%>
<!DOCTYPE
html
PUBLIC “-//W3C//DTD XHTML 1.0 Transitional//EN”
“http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd”>
<html><head
id=”Head1″ runat=”server”>
<title>Hello, master pages</title>
</head>
<body>
<form
id=”form1″ runat=”server”>
<asp:contentplaceholder
id=”PageBody” runat=”server”>
<!– derived pages will define content for this placeholder –>
</asp:contentplaceholder>
</form>
</body></html>
Derived Page(whose master has been set above) Source:
<%@
Page
Title=”" Language=”C#” MasterPageFile=”~/MasterPage.master” AutoEventWireup=”true” CodeFile=”Default2.aspx.cs” Inherits=”Default2″
%>
<asp:Content
ID=”Content1″ ContentPlaceHolderID=”PageBody” Runat=”Server”>
</asp:Content>
Here the link is established through the ContentPlaceHolderID =”PageBody”.
-
I want all the pages in my application derive from a single master page. How can we achieve this without specifying the MasterPage for each of these pages.
You can set this in the configuration file as below.
<configuration>
<system.web>
<pages
master=“MasterPage.master“ />
</system.web>
</configuration>
-
How to access a control in a MasterPage from a derived page.
This can be achieved through a combination of the Master Property and the @MasterType directive. Say for example I have a label in my master and I want to set the title of that label from my derived page. So I will add the @MasterType directive in my content page as follows
<%@
MasterType
VirtualPath=”~/Nested.master”
%>
Now you can access the control from the derived page as follows
Master.TitleBoxText = “This is the Master Page value”;