Matt Sigman

Hands-On Software Leader

Matt Sigman - Hands-On Software Leader

Add Dynamic Node to SiteMapProvider

Quick post to present a simple solution to the question:

How do you dynamically insert a node into an ASP.NET SiteMap?

I needed to do this for a project I was working on but all I found on Google were a bunch of way-too-complex solutions.  So I developed this simple approach and wanted to share it in hopes it helps someone in the same predicament.

First, create a new class that overrides the existing RouteBaseSitemapProvider class.  Add a new file to your solution and call it RouteBaseSitemapProvider.cs to keep things simple.  Paste this into your new class file:

using System.Collections.Generic;
using System.Text.RegularExpressions;
using System.Web;
using System.Web.Routing;
namespace MSigman.Web
{
    class RouteBaseSitemapProvider : XmlSiteMapProvider
    {
        private SiteMapNode _newCrumb;

        public void InsertNewBreadcrumb(string title, string url)
        {
            _newCrumb = new SiteMapNode(SiteMap.Provider, "newcrumb", url, title);
        }

        public override SiteMapNode CurrentNode
        {
            get
            {
                var node = base.CurrentNode;
                if (node != null)
                {
                    node = node.Clone(true);
                    if (_newCrumb != null)
                    {
                        var newNode = _newCrumb;
                        newNode.ParentNode = node.ParentNode;
                        node.ParentNode = newNode;
                    }
               }
               return node;
            }
        }
    }
}

Now that you have the class in place, you can call it from anywhere in your project as follows.

(SiteMap.Provider as RouteBaseSitemapProvider).InsertNewBreadcrumb(title, url);

And one last bit of plumbing code necessary to make it all work. In web.config, add the following lines to the system.web node.

    <siteMap defaultProvider="RouteBaseSitemapProvider">
      <providers>
        <add name="RouteBaseSitemapProvider" type="MSigman.RouteBaseSitemapProvider" siteMapFile="Web.sitemap" />
      </providers>
    </siteMap>

In my actual project I wrapped the call to InsertNewBreadcrumb() in a method nested in the Master page for the site, where the SiteMapPath control is located, but I left that out to keep this post straightforward.

Category: .NET

Your email address will not be published. Required fields are marked *

*