MVC Html Extension返回字符串而不是html标记?

如果我有这样的扩展名:

public static string ImageLink(this HtmlHelper htmlHelper, string imgSrc, string alt, string actionName, string controllerName, object routeValues, object htmlAttributes, object imgHtmlAttributes) { return @" "; } 

我在这样的局部视图中使用它:

 @Html.ImageLink("../../Content/images/english.png","English", "ChangeCulture", "Account", new { lang = "en", returnUrl = this.Request.RawUrl }, null,null) 

我有这样的输出: 在此处输入图像描述

知道为什么吗?

发生这种情况的原因是因为Razor中的@运算符会自动进行HTML编码。 如果要避免此编码,则需要使用IHtmlString

 public static IHtmlString ImageLink( this HtmlHelper htmlHelper, string imgSrc, string alt, string actionName, string controllerName, object routeValues, object htmlAttributes, object imgHtmlAttributes ) { return MvcHtmlString.Create(@""); } 

这显然会更正确(并且在所有情况下工作,无论从何处以及如何调用此帮助程序)如果这样写:

 public static IHtmlString ImageLink( this HtmlHelper htmlHelper, string imgSrc, string alt, string actionName, string controllerName, object routeValues, object htmlAttributes, object imgHtmlAttributes ) { var img = new TagBuilder("img"); var urlHelper = new UrlHelper(htmlHelper.ViewContext.RequestContext); img.Attributes["src"] = urlHelper.Content("~/Content/images/english.png"); // Don't forget that the alt attribute is required if you want to have valid HTML img.Attributes["alt"] = "English flag"; return MvcHtmlString.Create(img.ToString(TagRenderMode.SelfClosing)); } 

然后

 @Html.ImageLink("../../Content/images/english.png","English", "ChangeCulture", "Account", new { lang = "en", returnUrl = this.Request.RawUrl }, null,null) 

会正常工作。

如果您无法修改帮助程序,则可以使用@Html.Raw

 @Html.Raw(Html.ImageLink("../../Content/images/english.png","English", "ChangeCulture", "Account", new { lang = "en", returnUrl = this.Request.RawUrl }, null,null)) 

让它返回MvcHtmlString (我的示例如下)。

  public static MvcHtmlString IconImg(this HtmlHelper htmlHelper, string icon, string title = "", string size = "16x16") { string path = VirtualPathUtility.ToAbsolute("~/res/img/icons/" + size + "/" + icon + ".png"); string imgHtml = ""; return new MvcHtmlString(imgHtml); }