Site Map Driven Page Titles 

With the new SiteMap functionality wouldn't it be nice for all of your pages that are part of a master page to have a title that references their position in the site map and the values you have provided for the page titles? Well this is something that is fairly easy to implement, first ensure that your master page has the "runAt="Server"" declaration for the head element. Now once you have done that place the following code in the page codebehind. I will explain more in just a minute.

protectedvoid Page_Load(object sender, EventArgs e)
{
    
if (!IsPostBack)
    {
        
//Default Page title
        conststring DEFAULT_PAGE_TITLE = "Your Main Page Title";
        
        
//Check to see if the page is defined in the site map
        if (SiteMap.CurrentNode == null)
        {
            
//If not default title only
            Page.Title = DEFAULT_PAGE_TITLE;
        }
        
else
        {
            
//Build page title by walking the sitemap
            Page.Title = DEFAULT_PAGE_TITLE + " "
                    + GetPageTitleBasedOnSiteNavigation();
        }
    }
}

privatestring GetPageTitleBasedOnSiteNavigation()
{
    
string output = string.Empty;
    
SiteMapNode currentNode = SiteMap.CurrentNode;

    
while (currentNode != null)
    {
        
if (output.Length > 0)
            output = currentNode.Title +
" :: " + output;
        
else
            output = currentNode.Title;

        currentNode = currentNode.ParentNode;
    }

    
return output;
}

In the Page_load method we check to see if there is a siteMapNode for the current page, if not we set the page title to the default title, otherwise we walk through the nodes to the root of the sitemap building our page title.

The code snippet in this posting was colorized using a VS Macro provided by CodingHorror.com

Posted by Mitchel on Sunday, September 24, 2006
 

Comments

Currently, there are no comments. Be the first to post one!
Click here to post a comment

Donate

Show your appreciation for the content/modules made available by MitchelSellers.com by making a donation. Donations are used to assist with dedicating time to creating free content.