2010-06-18 17 views
3

我试图使用自定义帮助程序,该帮助程序使用在Is there an ASP.NET MVC HtmlHelper for image links?处找到的示例创建链接。将匿名(htmlAttributes)转换为IDictionary在自定义帮助程序时出错

假设这段代码实际上起作用,我不确定问题是什么。我是新来的匿名类型和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(); 
    } 

视图代码是这样的:

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

和异常:

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

回答

8

内部MVC使用RouteValueDictionary投对象转换成Dictionnary所以只需更改

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

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

这工作,谢谢! – bowlingforfish 2010-06-18 16:52:49

+0

@bowlingforfish:很高兴帮助,你应该接受答案... – 2010-06-18 17:24:25

+0

谢谢你的输入。今天我学到了很好的东西! – 2011-05-06 20:39:26