我正在尝试使用自定义帮助程序,使用在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 …Run Code Online (Sandbox Code Playgroud)