I ran into a problem developing an ASP.NET 2.0 app that at first seemed not to have a convenient solution. Then I discovered the SiteMap.SiteMapResolve event and the solution turned out to not be so difficult after all.

Here’s the problem. SiteMapPath controls in ASP.NET 2.0 automatically show the path to the current page provided the page is in the site map. But how do they handle the (fairly common) case in which several pages redirect or link to a common page and pass it a query string telling it what to display? Site map nodes must have unique URLs, so unless you’re willing to list that page in the site map with every possible query string value it will accept, you can’t include it in the site map. And if the current page doesn’t appear in the site map, then SiteMapPath won’t show the path to it.

Enter the SiteMap.SiteMapResolve event, which lets you add nodes to the site map on the fly. The trick is to register a handler for that event in the page’s Page_Load method, like this:

SiteMap.SiteMapResolve += new SiteMapResolveEventHandler (AddNode);

Then, in the event handler, you create a new SiteMapNode to represent the current page and parent it to an existing site map node, which you can obtain from the site map. Here’s a simple example that creates a new SiteMapNode and parents it to the site map’s root node:

public SiteMapNode AddNode (Object sender, SiteMapResolveEventArgs e)
SiteMapNode node = new SiteMapNode(SiteMap.Provider, “ThisPage.aspx”, “~/ThisPage.aspx”, “This Page”);
node.ParentNode = SiteMap.RootNode;
return node;

The only catch is that while the root site map node is easy to find, finding other nodes requires you to write a recursive method that searches the site map for the node that you want to parent the new node to. But that’s not hard, and it’s a small price to pay for being able to manipulate the site map at run-time.

[Note: Turns out you don’t have to write that recursive method after all. You can use the SiteMapProvider class’s FindSiteMapNode method. Thanks to Brian Goldfarb for pointing that out. — Jeff]

Given that real Web sites often don’t have purely hierarchical structures, I imagine a lot of developers will use this technique to make SiteMapPath controls work.