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

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

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 outputEnd 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 neededIf 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.

魔兽就是毒瘤,大家千万不要玩。
原文地址:https://www.cnblogs.com/tracy/p/1783000.html