2011-05-04 122 views
16

如果我有恩扩展这样的:MVC的Html扩展返回字符串,而不是HTML标记?

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

任何想法为什么?

回答

35

发生这种情况的原因是因为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)) 
15

它是否会返回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); 
    } 
+0

谢谢您的回答,我投您太:) – 2011-05-04 19:53:44

+0

的MvcHtmlString()创造了奇迹为我。谢谢 – 2013-10-18 16:58:32