June 17, 2009

Using a nested Master Page with ASP.Net

The first thing I actually missed from Webforms are nested masterpages. Fortunately they’re not missing at all, they just figured out those MVC guys (and galls) like code so much, they don’t need no stinkin’ templates for something as trivial as this. And of course we don’t. Here’s how to roll your own.

Masterpages are a great way to keep your webpages DRY. Repeating layout/markup/header stuff goes into the masterpage. This is great until you create a bigger site with more than one masterpage. Suddenly you’re repeating code between masterpages. So we go up one more level. We make a masterpage for the masterpages. Yes it’s tortoises all the way down.

We start with two normal masterpages. Master.Master and Child.Master. I’ve always been good in coming up with original names. They’ll both look a bit like this:

   1: <%@ Master Language="C#" Inherits="System.Web.Mvc.ViewMasterPage" %>
   2:  
   3: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
   4:  
   5: <html xmlns="http://www.w3.org/1999/xhtml" >
   6: <head runat="server">
   7:     <title><asp:ContentPlaceHolder ID="TitleContent" runat="server" /></title>
   8: </head>
   9: <body>
  10:     <div>
  11:         <asp:ContentPlaceHolder ID="MainContent" runat="server" />
  12:     </div>
  13: </body>
  14: </html>

Now we want Master.Master to look exactly like this. And we want Child.Master to look exactly like this but add “Child – “ before the title and we want the content of the child in VERY BIG LETTERS, so we’ll put a <h1> </h1> tag pair around the ‘MainContent’ contentplaceholder. I wanted to use <blink>, my favorite tag but it’s not supported anymore.

Of course we can just add all this to Child.Master and be done with it but we want to re-use the Master.Master code. So lets use Master.Master as a masterpage. This works just the way you’d expect. You just add a ‘MasterPageFile’ attribute to the Master tag and use ‘asp:Content’ tags to fill in the contentplaceholders. The big difference with content-pages is that you nest asp:ContentPlaceHolder tags inside the content. These can be filled in later by your pages. This is how your Child.Master will look.



   1: <%@ Master MasterPageFile="~/Views/Shared/Master.Master" Language="C#" Inherits="System.Web.Mvc.ViewMasterPage" %>
   2:  
   3: <asp:Content ID="TitleContent" ContentPlaceHolderID="MainContent" runat="server">
   4:     Child - <asp:ContentPlaceHolder ID="ContentPlaceHolder1" runat="server" />
   5: </asp:content>
   6:  
   7: <asp:Content ID="MainContent" ContentPlaceHolderID="MainContent" runat="server">
   8:     <h1>
   9:         <asp:ContentPlaceHolder ID="MainContent" runat="server" />
  10:     </h1>
  11: </asp:content>

Have fun!

No comments:

Post a Comment