我已经重写了这篇文章,使它更简单。这是我已经得到了代码(HtmlHelper
):SiteMap HtmlHelper ASP.NET MVC
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不存在。 tutorial不包括MVC Areas Lib,所以此问题的解决方案不起作用。
如果你检查我的编辑,你会看到它自动生成我的菜单基于HtmlHelper按照我链接到的文章的建议。根据你的翻译,我不确定,这对我个人而言是如何工作的。不过,我可以看到它背后的想法。 – Kezzer 2009-07-07 11:13:16