TheDeveloperBlog.com

Home | Contact Us

CSharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript

ASP.NET SiteMap Example

This ASP.NET article generates an HTML site map from the SiteMapProvider type.

SiteMap. A SiteMap represents pages with nodes.

We loop through a SiteMap and SiteMapDataSource for certain tasks, such as generating sidebar navigation. We present some skeleton code of a fast, graceful solution.

Example. We must start with a separate method. Using the SiteMapProvider, I constructed a C# class, which I put in the App_Code folder. Let us first look at a method that begins the recursion.

Method that accesses SiteMap: C#

void BeginMapTree()
{
    // Obtain a reference to the current sitemap's provider.
    SiteMapProvider map = SiteMap.Provider;

    // Begin the recursion.
    // Start at map.RootNode and with a depth of 0.
    MapTreeBuild(map.RootNode, map, 0);
}

Example 2. The next method uses recursion to walk through all SiteMap nodes, special casing nodes based on their Depth property. Nodes will be encountered in the expected, sequential order. We loop with a foreach-loop.

Also: We keep track of depth in a separate parameter, which we increase on each level of recursion.

Method that recursively reads SiteMap: C#

void MapTreeBuild(SiteMapNode nodeIn, SiteMapProvider provIn, int depth)
{
    // ... Build up a StringBuilder containing markup for a navigation sidebar.
    foreach (SiteMapNode node in provIn.GetChildNodes(nodeIn))
    {
	if (depth == 0)
	{
	    // ... Do something different on the first level of the tree.
	    _treeBuilder.AppendLine(node.Title);
	}
	else
	{
	    // ... Test if this node is the current node.
	    string styleClass;
	    if (SiteMap.CurrentNode.Equals(node))
	    {
		styleClass = "activeBucket";
	    }
	    else
	    {
		styleClass = "regularBucket";
	    }

	    // ... Do something with a regular item in the sitemap.
	    //     Here we append to a StringBuilder.
	    _treeBuilder.Append("<div>").Append(node.Title).Append("</div>");
	}
	MapTreeBuild(node, provIn, depth + 1);
    }
}

HtmlTextWriter. You can switch to a custom provider or data structure for your sitemap. It is effective to use HtmlTextWriter to build your HTML. You can easily use custom XML, or do cool things with LINQ on sitemaps.

HtmlTextWriter

Summary. We looked at methods that recursively search the SiteMap from ASP.NET web projects. A pre-made control may be easier to begin working with. But if you have a high-traffic site, your users will appreciate your more responsive site.

Tip: Use the recursive method presented here to eliminate heavy-weight ASP.NET controls.