Back to all posts

Site Map Driven Page Titles

Posted on Sep 24, 2006

Posted in category:
Development
ASP.NET

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 code-behind. 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.