How To: Programmatically Add Nodes to the SiteMap For Your .NET Site [Tips & Tricks] | Posted at 6:23 PM
The Web.sitemap file stores only static URLs, so if you have a page like this:
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
Home > News
News : My Site
Read on for how to solve it.
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 _mHeadline as String = String.Empty Sub Page_Load(sender as object, e as eventargs) handles me.load ' Here you set the page title to whatever dynamic thing ' you're loading. _mHeadline = "A test" AddHandler SiteMap.SiteMapResolve, AddressOf SiteMapResolve End Sub Protected Sub Page_Unload(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Unload ' Remove this specific handler once the page is done. ' Otherwise it will get called on other pages. RemoveHandler SiteMap.SiteMapResolve, AddressOf SiteMapResolve End Sub Protected Function SiteMapResolve(ByVal sender As Object, ByVal e As SiteMapResolveEventArgs) As SiteMapNode Dim cn As SiteMapNode = SiteMap.CurrentNode.Clone(True) Dim newNode As SiteMapNode ' "viewnews" can be changed to whatever you want. It's just a key. If _mViewTitle <> String.Empty Then newNode = New SiteMapNode(SiteMap.Provider, "viewnews", Request.Url.PathAndQuery, _mHeadline) newNode.ParentNode = cn Else newNode = cn End If Return newNode End Function
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.