我重写了这篇文章以使其更简单。这是我得到的代码(a HtmlHelper
):
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Runtime.CompilerServices;
using System.Web.Mvc;
using System.Text;
using System.Web.Routing;
namespace Intranet.Helpers
{
public static class MenuHelper
{
private static string GetBackLink(SiteMapNode parentNode)
{
return "<li class='li-back'><a href='" + parentNode.Url + "' title='" + parentNode.Title + "'></a></li>";
}
public static string Menu(this HtmlHelper helper)
{
var sb = new StringBuilder();
SiteMapNodeCollection siteMapNodeCollection;
sb.Append("<ul>");
SiteMapNode currentNode = SiteMap.CurrentNode;
if (!SiteMap.CurrentNode.Equals(SiteMap.RootNode))
{
if (!SiteMap.CurrentNode.HasChildNodes)
sb.Append(GetBackLink(SiteMap.CurrentNode.ParentNode.ParentNode));
else
sb.Append(GetBackLink(SiteMap.CurrentNode.ParentNode));
}
if (!SiteMap.CurrentNode.HasChildNodes)
siteMapNodeCollection = SiteMap.CurrentNode.ParentNode.ChildNodes;
else
siteMapNodeCollection = SiteMap.CurrentNode.ChildNodes;
foreach (SiteMapNode node in siteMapNodeCollection)
{
if(node.Description.Equals("hidden")) continue;
if (node.Url.Length == 0 && node.Description.Equals("separator"))
sb.Append("<li class=\"li-separator\"></li>");
else if (node.Url.Length == 0 && node.Description.Equals("heading"))
sb.Append("<li class=\"li-heading\">" + node.Title + "</li>");
else
{
if (node.HasChildNodes)
{
if (node.NextSibling != null)
sb.Append("<li class=\"li-sub\"><a href=\"" + node.Url + "\">" + node.Title + "</a></li>");
else
sb.Append("<li class=\"li-sub last-child\"><a href=\"" + node.Url + "\">" + node.Title + "</a></li>");
}
else
{
if (node.NextSibling != null)
sb.Append("<li><a href='" + node.Url + "'>" + node.Title + "</a></li>");
else
sb.Append("<li class='last-child'><a href='" + node.Url + "'>" + node.Title + "</a></li>");
}
}
}
sb.Append("</ul>");
return sb.ToString();
}
}
}
这是this的修改版本。我正在使用MVC Areas Lib,所以我看不到MvcSiteMap如何使用它,因为它不再{controller}/{action}
像以前那样工作。
假设我有一个类似的页面http://localhost/mycontroller/myaction
并且它存在于 SiteMap 中,那么菜单将很好地生成。但是假设我这样做http://localhost/mycontroller/myaction/50
并指定了一个参数,SiteMap 生成器将不再工作,因为该 URL 不存在。本教程不涵盖MVC Areas Lib,因此该问题的解决方案不起作用。