Wednesday, July 15, 2009

Add nodes dynamically to the SiteMap For Your ASP.NET Site

The Web.sitemap file stores only static URLs, so if you have a page like this:
http://yoursite.com/news.aspx?view=4

Your sitemap breadcrumb will not reflect the fact that you are viewing a an actual news item. If you're like me, you also reflect the breadcrumb in the title of your page. So instead of seeing:
Breadcrumb: Home > News > A headline! Title: A headline! : News : My Site
You see:
Home > News News : My Site
Read on for how to solve it.

Solution
How do you fix it? I found a
great post on how to nest the sitemap in a master-detail style and then adjust the parent node's URL, but I wanted to actually add a new node because I was viewing and listing news on the same page.
Here's how you do it:

private string _mHeadline = string.Empty;

protected void Page_Load(object sender, EventArgs e)
{

// Here you set the page title to whatever dynamic thing
// you're loading.
_mHeadline = "A test";


SiteMap.SiteMapResolve += SiteMapResolve;
}

protected void Page_Unload(object sender, System.EventArgs e)
{
// Remove this specific handler once the page is done.
// Otherwise it will get called on other pages.
SiteMap.SiteMapResolve -= SiteMapResolve;
}

protected SiteMapNode SiteMapResolve(object sender, SiteMapResolveEventArgs e)
{

SiteMapNode cn = SiteMap.CurrentNode.Clone(true);
SiteMapNode newNode = default(SiteMapNode);

// "viewnews" can be changed to whatever you want. It's just a key.
if (_mViewTitle != string.Empty) {
newNode = new SiteMapNode(SiteMap.Provider, "viewnews", Request.Url.PathAndQuery, _mHeadline);
newNode.ParentNode = cn;
}
else {
newNode = cn;
}

return newNode;
}

So I left out how I was getting the title of the news headline because I assume you know how to do that. The place that is interesting is the SiteMapResolve function. I create a new node and set its parent to the current node, which successfully has the SiteMapPath show the correct breadcrumb:
Home > News > A headline!

A couple notes:

First, I remove the handler once the page is complete because otherwise the function will get called every time the SiteMap resolves itself, which is not what we want!
Second, you may need to touch the web.config (just remove a line and undo it) and save it to have your application recycle itself, otherwise your changes might not show up.
Hope this helps somebody. Happy Programming!!!

Reference:

http://blog.lib.umn.edu/ayubx003/dividebyzero/2009/01/10/how_to_programmatically_add_no.html#more


No comments: