我試圖從this關注自定義圖像鏈接助手的堆棧溢出問題。代碼起作用,只要我刪除.MergeAttributes
命令。當使用時,該命令鼓起,投擲以下異常無法投射'<> f__AnonymousType1`1 [System.String]'類型的對象來鍵入
無法轉換類型 '<> f__AnonymousType1
1[System.String]' to type 'System.Collections.Generic.IDictionary
2 [System.String,System.String]' 的對象。
下面是我使用的helper類的代碼。這個想法是隻使用兩個字符串值作爲輸入參數,而任何其他HTML/img標籤屬性作爲輸入對象的屬性輸入。
public static MvcHtmlString ImageLink(this HtmlHelper htmlHelper, string imgSrc, string url, object imgAttributes, object htmlAttributes)
{
UrlHelper urlHelper = ((Controller)htmlHelper.ViewContext.Controller).Url;
var imgTag = new TagBuilder("img");
imgTag.MergeAttribute("src", imgSrc);
imgTag.MergeAttributes((IDictionary<string, string>)imgAttributes, true); //Exception thrown here
var imgLink = new TagBuilder("a");
imgLink.MergeAttribute("href", url);
imgLink.InnerHtml = imgTag.ToString();
imgLink.MergeAttributes((IDictionary<string, string>)htmlAttributes, true);
return MvcHtmlString.Create(imgLink.ToString());
}
這裏是來自Razor/.cshtml文件的代碼。
@Html.ImageLink(Url.Content("~/Content/images/Screen.PNG"), System.Configuration.ConfigurationManager.AppSettings["Periscope"],
new {title="Search Periscope"} , new { target="_blank"})
優秀的以下行
,謝謝! – NealR