When you think ASP, think...
Recent Articles
All Articles
ASP.NET Articles [1.x] [2.0]
ASPFAQs.com
Message Board
Related Web Technologies
User Tips!
Coding Tips
Search

Sections:
Book Reviews
Sample Chapters
Commonly Asked Message Board Questions
Headlines from ASPWire.com
JavaScript Tutorials
MSDN Communities Hub
Official Docs
Security
Stump the SQL Guru!
Web Hosts
XML
Information:
Advertise
Feedback
Author an Article
Jobs
















internet.com
IT
Developer
Internet News
Small Business
Personal Technology
International

Search internet.com
Advertise
Corporate Info
Newsletters
Tech Jobs
E-mail Offers
ASP ASP.NET ASP FAQs Message Board Feedback ASP Jobs
Print this Page!

Windows Systems Administrator
Jupitermedia
US-CT-Darien

Justtechjobs.com Post A Job | Post A Resume

Published: Wednesday, May 10, 2006

Dynamically Setting the Page's Title in ASP.NET 2.0
By Scott Mitchell


Introduction
The HTML standard defines a number of metadata elements that can optionally be added to a web page. One of the most common is the <title> element, which appears in the <head> element and names the page. The value of the title, if provided, appears in the browser's Window title bar and also is the default name provided when bookmarking a web page. Moreover, many search engines display the page's title as the clickable link when it appears in the results. For these reasons, from a web developer standpoint, it's important that the page's title be assigned to a descriptive, meaningful value.

While the <title> can be set statically in an ASP.NET web page, in many scenarios the title is dependent upon the data displayed in the page. For example, a website might have a ShowProduct.aspx?ID=productID page. Rather than using a static <title>, the value of the <title> would ideally be the name of the product being viewed (that is, the product whose ProductID equaled the productID value passed through the querystring). Unfortunately, in ASP.NET version 1.x, setting any HTML metadata elements (such as <title>) required that the developer add a Literal control in the proper place in the HTML markup and then set its value programmatically in the ASP.NET page's code-behind class.

With ASP.NET 2.0, ASP.NET pages can include a <head> section whose values can be read and assigned programmatically. In this article we'll examine specifically how to dynamically set the page's title. We'll also look at a method that you can include in your master page or a base page class to automatically set the title based upon the site map information (similar to how the SiteMapPath control works). Read on to learn more!

- continued -

Creating a Programmatically-Accessible <head> Region
One of the many new features found in ASP.NET 2.0 is the programmatically-accessible <head> region, which can be added to an ASP.NET page using the following markup:

<head runat="server">
    <title>Untitled Page</title>
    
    ... other <head>-level elements ...
</head>

The above markup (less the"... other <head>-level elements ..." part) is what Visual Studio adds to a new ASP.NET page or master page, by default. Note the runat="server". When an ASP.NET page is requested, the ASP.NET engine parses the HTML portion and creates the page's control hierarchy. During this process, the markup that maps to server-side controls is converted into an appropriate object instance. For example, during this process the TextBox Web control's markup is parsed (<asp:TextBox runat="server" id="myTextBox" ... />) and a TextBox class instance is created to participate during the events of the page's lifecycle.

The runat="server" portion is what instructs the ASP.NET engine that a particular piece of markup is a server-side control versus static HTML. The <head runat="server"> markup is instantiated as an HtmlHead class instance, which has properties mapping to <head>-level settings, including:

  • Title - the page's title
  • Style - a collection of cascading style sheet (CSS) entries defined for the page
In order to be able to programmatically access these <head>-level settings, you need to be certain to add the <head runat="server"> to your ASP.NET page or master page, if it's not present already.

Programmatically Working with the <head> Region
Assuming you have a programmatically-accessible <head> region defined in your page or the page's master page, you can programmatically access it using the Page class's Header property. For example, to programmatically set the title of a page, add the following line of code to the page's Page_Load event handler:

Page.Header.Title = "The current time is: " & DateTime.Now.ToString()

Alternatively, you can use the Page.Title property as a shortcut to Page.Header.Title. Furthermore, if you are using master pages, this code can work, as written, from either the master page or the ASP.NET page that uses the master page. In such a scenario, the <head> region should be defined in the master page, but the ASP.NET page can still access it via Page.Header.

Assigning the Page Title Based on Site Map Data
Another new feature of ASP.NET 2.0 is the site map, a topic discussed in length in my Examining ASP.NET 2.0's Site Navigation article series. Rather than have to manually or programmatically set the page title for every page on a one-by-one basis, it's easy to instead have the page title set programmatically based upon the site map structure and the page being requested. For example, imagine that our site has a site map with the following logical structure defined:

The site map structure.

With just a few lines of code we can create a method in the master page that will automatically generate and assign an appropriate title to the requested page's title. With this method (which we'll examine shortly), when a person visits the homepage, the title would be set to "Amazon.com Homepage". When they visited the Books page, the title would be "Amazon.com Homepage :: Books", and when they visited the Novels page the title would be "Amazon.com Homepage :: Books :: Novels".

To accomplish this, we need to create a method that accesses the node being visited in the site map and then walks up the site map hierarchy until it reaches the root. Finally, the Titles for each SiteMapNode instance enumerated must be concatenated to form the title. The SiteMapNode that maps to the currently requested page can be accessed via the SiteMap class's CurrentNode property. The hierarchy can be walked up using the SiteMapNode's ParentNode property until the root is reached.

The following method uses string concatenation to achieve this aim. Included in the download at the end of this article is another implementation of this method that uses recursion.

Private Function GetPageTitleBasedOnSiteNavigation() As String
    If SiteMap.CurrentNode Is Nothing Then
        Throw New ArgumentException("currentNode cannot be Nothing")
    End If

    'We are visiting a page defined in the site map - build up the
    'page title based on the site map node's place in the hierarchy

    Dim output As String = String.Empty
    Dim currentNode As SiteMapNode = SiteMap.CurrentNode

    While currentNode IsNot Nothing
        If output.Length > 0 Then
            output = currentNode.Title & " :: " & output
        Else
            output = currentNode.Title
        End If

        currentNode = currentNode.ParentNode
    End While

    Return output
End Function

This method assumes that SiteMap.CurrentNode will not be Nothing. This value may be Nothing if the page being requested is not defined in the site map. Assuming SiteMap.CurrentNode is not nothing, the method walks up the site map hierarchy pre-pending the current SiteMapNode's Title to the string variable output. Once currentNode is nothing - meaning that we've just processed the root - output is returned.

This method can be utilized from the master page's Page_Load event handler using the following code:

'Constants defining title for "unnamed" page and 
Const DEFAULT_UNNAMED_PAGE_TITLE As String = "Untitled Page"
Const DEFAULT_PAGE_TITLE As String = "Welcome to my Website!!"

'Set the page's title, if needed
If String.IsNullOrEmpty(Page.Title) OrElse _
   Page.Title = DEFAULT_UNNAMED_PAGE_TITLE Then
    
    If SiteMap.CurrentNode Is Nothing Then
        Page.Title = DEFAULT_PAGE_TITLE
    Else
        Page.Title = GetPageTitleBasedOnSiteNavigation()
    End If
    
End If

To see this code in C#, check out my blog entry, Displaying a Breadcrumb in the Page's Title...

This code only sets the Page.Title property to the return value from GetPageTitleBasedOnSiteNavigation() if the page title has not been set or its set to the default Visual Studio value, "Untitled Page". If, however, SiteMap.CurrentNode is Nothing, instead of calling GetPageTitleBasedOnSiteNavigation() the page's title is set to "Welcome to my Website!!" (although feel free to change this to something more applicable for your website).

Conclusion
In this article we saw how to programmatically work with a page's title in an ASP.NET 2.0 page. Although we did not explore it in this article, the <head> element's cascading stylesheet (CSS) elements can also be programmatically accessed much in the same manner. This article concluded with a look at a method that sets the page's title based upon the requested page and its position in the site map hierarchy. This method, along with a complete working example, can be downloaded at the end of this article.

Happy Programming!

  • By Scott Mitchell


    Attachments

  • Download the code used in this article


    Windows Internet Technology | ASP.NET [1.x] [2.0] | ASPMessageboard.com | ASPFAQs.com | Advertise | Feedback | Author an Article



  • JupiterOnlineMedia

    internet.comearthweb.comDevx.commediabistro.comGraphics.com

    Search:

    Jupitermedia Corporation has two divisions: Jupiterimages and JupiterOnlineMedia

    Jupitermedia Corporate Info


    Legal Notices, Licensing, Reprints, & Permissions, Privacy Policy.

    Advertise | Newsletters | Tech Jobs | Shopping | E-mail Offers

    Solutions
    Whitepapers and eBooks
    Microsoft Article: HyperV-The Killer Feature in WinServer ‘08
    Avaya Article: How to Feed Data into the Avaya Event Processor
    Microsoft Article: Install What You Need with Win Server ‘08
    HP eBook: Putting the Green into IT
    Whitepaper: HP Integrated Citrix XenServer for HP ProLiant Servers
    Intel Go Parallel Portal: Interview with C++ Guru Herb Sutter, Part 1
    Intel Go Parallel Portal: Interview with C++ Guru Herb Sutter, Part 2--The Future of Concurrency
    Avaya Article: Setting Up a SIP A/S Development Environment
    IBM Article: How Cool Is Your Data Center?
    Microsoft Article: Managing Virtual Machines with Microsoft System Center
    HP eBook: Storage Networking , Part 1
    Microsoft Article: Solving Data Center Complexity with Microsoft System Center Configuration Manager 2007
    MORE WHITEPAPERS, EBOOKS, AND ARTICLES
    Webcasts
    Intel Video: Are Multi-core Processors Here to Stay?
    On-Demand Webcast: Five Virtualization Trends to Watch
    HP Video: Page Cost Calculator
    Intel Video: APIs for Parallel Programming
    HP Webcast: Storage Is Changing Fast - Be Ready or Be Left Behind
    Microsoft Silverlight Video: Creating Fading Controls with Expression Design and Expression Blend 2
    MORE WEBCASTS, PODCASTS, AND VIDEOS
    Downloads and eKits
    Sun Download: Solaris 8 Migration Assistant
    Sybase Download: SQL Anywhere Developer Edition
    Red Gate Download: SQL Backup Pro and free DBA Best Practices eBook
    Red Gate Download: SQL Compare Pro 6
    Iron Speed Designer Application Generator
    MORE DOWNLOADS, EKITS, AND FREE TRIALS
    Tutorials and Demos
    How-to-Article: Preparing for Hyper-Threading Technology and Dual Core Technology
    eTouch PDF: Conquering the Tyranny of E-Mail and Word Processors
    IBM Article: Collaborating in the High-Performance Workplace
    HP Demo: StorageWorks EVA4400
    Intel Featured Algorhythm: Intel Threading Building Blocks--The Pipeline Class
    Microsoft How-to Article: Get Going with Silverlight and Windows Live
    MORE TUTORIALS, DEMOS AND STEP-BY-STEP GUIDES