Tuesday, October 27, 2009

Nested Master Pages

I have two master pages, one that uses a two column layout, and one that uses a three column layout. So instead of duplicating the entire file (ASP.NET file tags, XML file tags, script tags, css link tags, header and footer controls, etc) I did some googling and discovered that you can build master pages from a base master page (the derived master pages = nested master pages), much like you can create a base ASPX page and use the content place holder control as a template to vary the content. Yay!

One important detail though, is that the nested master pages need to inherit either from the vanilla master page class or a custom master page class (not the base master page class!!!), and the base master page should inherit from the vanilla master page class or a custom master page class

http://msdn.microsoft.com/en-us/library/x2b3ktt7.aspx

This is the parent master file:
<% @ Master Language="C#" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML
1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html>
<head runat="server">
<title>Untitled Page</title>
</head>
<body>
<form id="Form1" runat="server">
<div>
<h2>Parent Master</h2>
<p style="font:color=red">This is parent master content.</p>
<asp:ContentPlaceHolder ID="MainContent" runat="server" />
</div>
</form>
</body>
</html>

This is the child master file:

<%@ Master Language="C#" MasterPageFile="~/Parent.master"%>
<asp:Content id="Content1" ContentPlaceholderID="MainContent" runat="server">
<asp:panel runat="server" id="panelMain" backcolor="lightyellow">
<h2>Child master</h2>
<asp:panel runat="server" id="panel1" backcolor="lightblue">
<p>This is child master content.</p>
<asp:ContentPlaceHolder ID="ChildContent1" runat="server" />
</asp:panel>
<asp:panel runat="server" id="panel2" backcolor="pink">
<p>This is child master content.</p>
<asp:ContentPlaceHolder ID="ChildContent2" runat="server" />
</asp:panel>
<br />
</asp:panel>
</asp:Content>

And finally, regular page that references the child master file:

<%@ Page Language="C#" MasterPageFile="~/Child.master"%>
<asp:Content id="Content1" ContentPlaceholderID="ChildContent1" runat="server">
<asp:Label runat="server" id="Label1"
text="Child label1" font-bold="true" />
<br />
</asp:Content>
<asp:Content id="Content2" ContentPlaceholderID="ChildContent2" runat="server">
<asp:Label runat="server" id="Label2"
text="Child label2" font-bold="true"/>
</asp:Content>