recently I have moved to ASP.NET MVC and I was also interested, how to create menu. I have found only 1 suitable help (http://www.asp.net/mvc/tutorials/providing-website-navigation-with-sitemaps-cs). This tutorial creates menu using Web.sitemap. But if you would try to create the menu with this help, you will see that it is not suitable for "more level" menus. So I have modified this code and created this.
using System.Text;
using System.Web;
using System.Web.Mvc;
public static class MenuHelper
{
public static MvcHtmlString Menu(this HtmlHelper helper)
{
var sb = new StringBuilder();
sb.Append("<div id='menu'><ul>");
var topLevelNodes = SiteMap.RootNode.ChildNodes;
foreach (SiteMapNode node in topLevelNodes)
{
sb.AppendLine(SiteMap.CurrentNode == node ? "<li class='selectedMenuItem'>" : "<li>");
sb.AppendFormat("<a href='{0}'>{1}</a>", node.Url, helper.Encode(node.Title));
BuildMenu(sb, node);
sb.AppendLine("</li>");
}
sb.AppendLine("</ul></div>");
return MvcHtmlString.Create(sb.ToString());
}
private static StringBuilder BuildMenu(StringBuilder sb, SiteMapNode node)
{
if (node.ChildNodes.Count != 0)
{
sb.Append("<ul>");
foreach (SiteMapNode childNode in node.ChildNodes)
{
sb.AppendLine(SiteMap.CurrentNode == childNode ? "<li class='selectedMenuItem'>" : "<li>");
sb.AppendFormat("<a href='{0}'>{1}</a>", childNode.Url, childNode.Title);
BuildMenu(sb, childNode);
sb.AppendLine("</li>");
}
sb.AppendLine("</ul>");
}
return sb;
}
}
In the View you write only @Html.Menu(). Remember to create Web.sitemap and also insert your pages into. Hope it helps!