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

时间:2011-05-04 19:31:37

标签: c# asp.net asp.net-mvc-3 razor

如果我有这样的扩展名:

 public static string ImageLink(this HtmlHelper htmlHelper,
                                      string imgSrc, 
                                      string alt, 
                                      string actionName,
                                      string controllerName, 
                                      object routeValues, 
                                      object htmlAttributes, 
                                      object imgHtmlAttributes)
  {

     return @"<img src=""../../Content/images/english.png"" /> ";
  }

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

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

我有这样的输出: enter image description here

知道为什么吗?

2 个答案:

答案 0 :(得分:37)

发生这种情况的原因是因为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(@"<img src=""../../Content/images/english.png"" />");
}

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

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))

答案 1 :(得分:16)

让它返回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 = "<img src='" + path + "' title='" + title + "' style='border:none' />";
        return new MvcHtmlString(imgHtml);
    }