2011-05-04 104 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