Domanda

I want to get the url from the Mvc.sitemap file using a attribute like "key"? I want call it from a helper. I just can't figure out how to retrieve a node from the file using mvcsitemap classes to generate the url. Thanks in advance!

È stato utile?

Soluzione

2 hours later and 4 hours total here it goes:

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;
    }
}

Now all you need to do is call @Html.MvcSiteMap().GetNodeByKey("mykey").Url

Not just url but all other properties are available (title, ImageUrl, targetFrame..) and you can create also a helper to write the complete anchor link using the url and title.

UPDATED: If you were wondering, here goes the code for the link helper:

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);
    }
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top