如何使用MvcSiteMapProvider从Mvc.sitemap获取节点的url

时间:2012-03-05 23:53:00

标签: c# asp.net-mvc-3 mvcsitemapprovider

我想使用像“key”这样的属性从Mvc.sitemap文件中获取网址?我想从帮助者那里打电话。我只是无法弄清楚如何使用mvcsitemap类从文件中检索节点来生成url。 提前谢谢!

1 个答案:

答案 0 :(得分:6)

2小时后总计4小时:

public static class MyHelpers
{
    private static Dictionary<string, object> SourceMetadata = new Dictionary<string, object> { { "HtmlHelper", typeof(MenuHelper).FullName } };

    public static MvcSiteMapNode GetNodeByKey(this MvcSiteMapHtmlHelper helper, string nodeKey)
    {
        SiteMapNode node = helper.Provider.FindSiteMapNodeFromKey(nodeKey);

        var mvcNode = node as MvcSiteMapNode;

        return mvcNode;
    }
}

现在您需要做的就是调用@ Html.MvcSiteMap()。GetNodeByKey(“mykey”)。Url

不仅仅是url,而且所有其他属性都可用(title,ImageUrl,targetFrame ..),您还可以创建一个帮助程序,使用url和title编写完整的锚链接。

更新:如果你想知道,这里是链接助手的代码:

public static MvcHtmlString MapLink(this MvcSiteMapHtmlHelper htmlHelper, string nodeKey)
    {
        return htmlHelper.MapLink(nodeKey, null, null);
    }
    public static MvcHtmlString MapLink(this MvcSiteMapHtmlHelper htmlHelper, string nodeKey, string linkText)
    {
        return htmlHelper.MapLink(nodeKey, linkText, null);
    }
    public static MvcHtmlString MapLink(this MvcSiteMapHtmlHelper htmlHelper, string nodeKey, string linkText, object htmlAttributes)
    {
        MvcSiteMapNode myNode = GetNodeByKey(htmlHelper, nodeKey);
        //we build the a tag
        TagBuilder builder = new TagBuilder("a");
        // Add attributes
        builder.MergeAttribute("href", myNode.Url);
        if (htmlAttributes != null)
        {
            builder.MergeAttributes(new RouteValueDictionary(htmlAttributes), true);
        }
        if (!string.IsNullOrWhiteSpace(linkText))
        {
            builder.InnerHtml = linkText;
        }
        else
        {
            builder.InnerHtml = myNode.Title;
        }
        string link = builder.ToString();
        return  MvcHtmlString.Create(link);
    }