Access to a page's head element using ASP.NET 2.0

One of the small, but nice, feature additions in ASP.NET 2.0 is support for a <head runat="server"> tag that you can access via the page object's "Header" property.  This is added by default to a page when you create a new one with Visual Web Developer or VS 2005.  You can then programmatically access it like so:

C#:

    this.Header.Title = "I just set the page's title";

VB:

    Me.Header.Title = "And in VB too!";

Ryan Farley just posted a nice summary that shows off a few cool uses of it (setting titles, CSS style rules and adding stylesheet links).  You can read his post here.

Raj posted a great comment on this post, about how you can add code to your master page to pull the title out of the Site Navigation system and set the title programmatically like so:

     this.Page.Title = SiteMap.CurrentNode.Title;

This allows you to store the title of a page separate from the file itself.  You can learn more about the ASP.NET 2.0 Site Navigation system here.

I was talking with Dmitry earlier today, and he mentioned that he was planning to update his extremely cool RSS Toolkit for ASP.NET to have the <RSSToolkit:RSSHyperlink> control use the <head runat="server"> feature to automatically add the appropriate RSS feed meta-data to a page so that browsers and news-readers can automatically find and subscribe to the feed it points to.  He is hoping to include this in a new update to the RSS toolkit he is planning over the next few days.

Hope this helps,

Scott

Update: Sue posted a very useful article that lists more ways to use the <head> control here.

Published Friday, March 24, 2006 8:51 PM by ScottGu
Filed under:

Comments

# re: Access to a Page's <head> tag using ASP.NET 2.0

Saturday, March 25, 2006 12:08 AM by Raj Kaimal
I have been using this on the master page like so:
this.Page.Title = SiteMapDataSource1.Provider.CurrentNode.Title;

Works great.

# re: Access to a page's head element using ASP.NET 2.0

Monday, March 27, 2006 9:52 AM by Wouter
I think this is a very nice feature. We use it for a RegisterStylesheet functionality (similar to RegisterClientScript) so we can add a stylesheet in a page but the LINK element will be added in the HEAD section present in the masterpage.

By the way: my VB is a bit rusty, but are you sure you need to end that VB line with a semicolon? ;-)

# re: Access to a page's head element using ASP.NET 2.0

Friday, April 14, 2006 10:08 AM by Magnus
You've forgot to remove the ';' in the VB code.

# re: Access to a page's head element using ASP.NET 2.0

Thursday, August 10, 2006 3:16 AM by Roy
how do you do this in asp.net 1.1?