bowlingforfish
bowlingforfish

Reputation: 43

Error converting anonymous (htmlAttributes) to IDictionary in custom helper

I'm trying to use a custom helper that creates a link using the example found at Is there an ASP.NET MVC HtmlHelper for image links?.

Going on the assumption that this code actually functions, I'm not sure what the problem is. I'm new to anonymous types and MVC, so am assuming I'm missing something glaringly obvious.

My code looks like such:

        public static string ImageLink(this HtmlHelper htmlHelper, string imgSrc, string alt, string actionName, string controllerName, object imgHtmlAttributes)
    {
        UrlHelper urlHelper = ((Controller)htmlHelper.ViewContext.Controller).Url;
        TagBuilder imgTag = new TagBuilder("img");
        imgTag.MergeAttribute("src", imgSrc);
        imgTag.MergeAttributes((IDictionary<string, string>)imgHtmlAttributes, true);
        string url = urlHelper.Action(actionName, controllerName);

        TagBuilder imglink = new TagBuilder("a");
        imglink.MergeAttribute("href", url);
        imglink.InnerHtml = imgTag.ToString();

        return imglink.ToString();
    }

The view code is this:

<%= Html.ImageLink("../../imgs/details_icon", "View details", "Details", "Tanque", new { height = "5", width = "5" }) %>

And the exception:

Unable to cast object of type '<>f__AnonymousType0`2[System.String,System.String]' to type 'System.Collections.Generic.IDictionary`2[System.String,System.String]'.

Upvotes: 3

Views: 1297

Answers (1)

moi_meme
moi_meme

Reputation: 9318

Internally MVC uses RouteValueDictionary to cast object into Dictionnary so simply change

imgTag.MergeAttributes((IDictionary<string, string>)imgHtmlAttributes, true);

to

imgTag.MergeAttributes(new RouteValueDictionary(imgHtmlAttributes), true);

Upvotes: 8

Related Questions