2

我想使用“key”之类的属性从 Mvc.sitemap 文件中获取 url?我想从帮手那里打电话。我只是不知道如何使用 mvcsitemap 类从文件中检索节点以生成 url。提前致谢!

4

1 回答 1

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 和标题编写完整的锚链接。

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

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);
    }
于 2012-03-06T12:24:01.340 回答