Header Ads Widget

Ticker

6/recent/ticker-posts

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


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 productIDvalue 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). 

ASP.NET - 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.

ASP.NET - 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 callingGetPageTitleBasedOnSiteNavigation() the page's title is set to "Welcome to my Website!!" (although feel free to change this to something more applicable for your website).

ASP.NET - 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.

Post a Comment

0 Comments