views:

26

answers:

1

I'm trying to use a custom helper that creates a link using the example found at http://stackoverflow.com/questions/675319/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]'.
A: 

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);
moi_meme
That worked, thanks!
bowlingforfish
@bowlingforfish: Glad to help, you should then accept the answer...
moi_meme