在自定义帮助程序中将匿名(htmlAttributes)转换为IDictionary时出错

bow*_*ish 3 c# asp.net-mvc-2

我正在尝试使用自定义帮助程序,使用在ASP.NET MVC HtmlHelper中找到的示例创建链接用于图像链接?.

假设这段代码实际起作用,我不确定问题是什么.我是匿名类型和MVC的新手,所以假设我错过了一些明显的东西.

我的代码看起来像这样:

        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();
    }
Run Code Online (Sandbox Code Playgroud)

视图代码是这样的:

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

例外情况:

Unable to cast object of type '<>f__AnonymousType0`2[System.String,System.String]' to type 'System.Collections.Generic.IDictionary`2[System.String,System.String]'.
Run Code Online (Sandbox Code Playgroud)

moi*_*eme 8

内部MVC使用RouteValueDictionary将对象强制转换为Dictionnary,因此只需更改即可

imgTag.MergeAttributes((IDictionary<string, string>)imgHtmlAttributes, true);
Run Code Online (Sandbox Code Playgroud)

imgTag.MergeAttributes(new RouteValueDictionary(imgHtmlAttributes), true);
Run Code Online (Sandbox Code Playgroud)