British Inside

An Englishman living in small town America

James Shaw

News

  • Copyright James Shaw 2004-2007

    Creative Commons License

    View James Shaw's profile on LinkedIn

Nested Master Pages and ScriptsEtc

I only started working with ASP.NET 2.0's master pages yesterday (it seems longer) but I just finished the conversion - or let's say RC1 of the conversion.

One interesting thing I found was that many people have settled for adding data to the Head from code rather than declaratively. Instantiating an HtmlLink and adding it to the Page.Header.Controls collection for example.

I'm not a fan of that because if you don't have the source you are stuck. I'd prefer to do as much as possible in the .aspx and .master.

I have some aspx pages that do special things, and add their own scripts/css/etc to the mix. How to declare them in the aspx, but roll them into the Head of the master page?

I started by adding another contentplaceholder called ScriptsEtc into basic.master, with the intent that the aspx will simply fill that content in if necessary:

basic.master:

<head runat="server">
   <asp:contentplaceholder id="ScriptsEtc" runat="server" />
</head>

.aspx:

<asp:content contentplaceholderid="ScriptsEtc" runat="server">
   <script language="javascript" src="something.js" />
</asp:content>

That works great, except that I have nested master pages that might work like this: basic.master > boxed.master > tb.master > lrtb.master > blogs.master - and referencing ScriptsEtc when your defined master page is blogs.master doesn't work. You can't reference a contentplaceholder if it isn't in your defined master page.

So, to get around this (and you'll speak up if there is a better way), I added the following to the bottom of all my masters:

<asp:content contentplaceholderid="ScriptsEtc" runat="server">
   <asp:contentplaceholder id="ScriptsEtc" runat="server" />
</asp:content>

I can then declaratively fill in the ScriptsEtc content from my aspx with whatever scripts or css that I want to place into the Head.


Posted: Wednesday, August 30, 2006 10:43 AM by James

Comments

David said:

Excellent idea! It works great for me!
# March 2, 2007 8:26 AM
New Comments to this post are disabled