Blogs

Site Map Driven Page Titles

24 Sep

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.

protected void Page_Load(object sender, EventArgs e)
{
    
if (!IsPostBack)
    {
        
//Default Page title
        const string 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();
        }
    }
}

private string 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

tags: Tutorials, ASP.NET
comments powered by Disqus

Content provided in this blog is provided "AS-IS" and the information should be used at your own discretion.  The thoughts and opinions expressed are the personal thoughts of Mitchel Sellers and do not reflect the opinions of his employer.

Connect with Mitchel

I hope the information here has been helpful. To stay connected you can also subscribe to blog updates via email, contact Mitchel about consulting services, or reach out for assistance via CodeMendor

Content Copyright

Content in this blog is copyright protected.  Re-publishing on other websites is allowed as long as proper credit and backlink to the article is provided.  Any other re-publishing or distribution of this content is prohibited without written permission from Mitchel Sellers.