ASP.NET: Setup the Page Title from Web.Sitemap

Wednesday, August 04, 2010

ASP.Net allows you to associate a sitemap file with your project. You can add this file as a Web.Sitemap in the web project. This file could be used with the ASP.Net navigation controls to create menu, tree view or a site map path on your website. One of the other things where this file comes handy is when you want to dynamically assign title to your pages. This is a fairly common requirement when you use master pages and don't want to modify additional parameters on individual pages. Here's the code you should add into your master page's .cs file:

// C#
protected override void OnInit(System.EventArgs e)
{
base.OnInit(e);

// Setting Page Title from SiteMap
SiteMapNode node = SiteMap.CurrentNode;

if (node != null && !string.IsNullOrEmpty(node.Title))
{
Page.Title = "App Name | " + node.Title;
}
}
' VB.NET
Protected Overrides Sub OnInit(e As System.EventArgs)
MyBase.OnInit(e)

' Setting Page Title from SiteMap
Dim node As SiteMapNode = SiteMap.CurrentNode

If node IsNot Nothing AndAlso Not String.IsNullOrEmpty(node.Title) Then
Page.Title = "App Name | " + node.Title
End If
End Sub

The above function adds the associated title associated with the url of the page.