Pat*_*ins 17 c# asp.net razor asp.net-mvc-3
如果我有这样的扩展名:
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"" /> ";
}
Run Code Online (Sandbox Code Playgroud)
我在这样的局部视图中使用它:
@Html.ImageLink("../../Content/images/english.png","English", "ChangeCulture", "Account", new { lang = "en", returnUrl = this.Request.RawUrl }, null,null)
Run Code Online (Sandbox Code Playgroud)
我有这样的输出:

知道为什么吗?
Dar*_*rov 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"" />");
}
Run Code Online (Sandbox Code Playgroud)
这显然会更正确(并且在所有情况下工作,无论从何处以及如何调用此帮助程序)如果这样写:
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));
}
Run Code Online (Sandbox Code Playgroud)
然后
@Html.ImageLink("../../Content/images/english.png","English", "ChangeCulture", "Account", new { lang = "en", returnUrl = this.Request.RawUrl }, null,null)
Run Code Online (Sandbox Code Playgroud)
会正常工作.
作为替代方案,如果您无法修改帮助程序,则可以使用@Html.Raw:
@Html.Raw(Html.ImageLink("../../Content/images/english.png","English", "ChangeCulture", "Account", new { lang = "en", returnUrl = this.Request.RawUrl }, null,null))
Run Code Online (Sandbox Code Playgroud)
Mar*_*arz 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);
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
16061 次 |
| 最近记录: |