ASP.NET SiteMap Example

Note

You want to recurse through the notes in your ASP.NET sitemap. Loop through your SiteMap and SiteMapDataSource for certain tasks, such as generating sidebar navigation. We present some skeleton code of a better-performing, more graceful solution than the TreeView or the Repeater controls in ASP.NET.

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

Recurse through nodes

We must start with a separate method. Using the SiteMapProvider, I constructed a C# class, which I put in the App_Code folder. Let's look at 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, starting at map.RootNode and with a depth of 0.
    MapTreeBuild(map.RootNode, map, 0);
}

Evaluate all nodes

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. 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)
{
    // In this example, we 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
	{
	    // Here is a way to 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 simply
	    // append to a StringBuilder, which stores the result.
	    _treeBuilder.Append("<div>").Append(node.Title).Append("</div>");
	}
	MapTreeBuild(node, provIn, depth + 1);
    }
}

More complete solution

Programming tip

You can switch to a custom provider or data structure for your sitemap. It would also be good to use HtmlTextWriter to build your HTML. You can use custom XML in C# very easily, or do cool things with LINQ on sitemaps.

HtmlTextWriter Use

Summary

The C# programming language

We looked at methods that recursively search the SiteMap from ASP.NET web projects in the C# language. A pre-made control may be easier to begin working with, but if you have a high-traffic or critical site, your users will greatly appreciate your more responsive site. Use the recursive method presented here to eliminate heavy-weight ASP.NET controls.

ASP.NET Tutorials
.NET