MVC HTML扩展返回的字符串,而不是HTML标记? [英] MVC Html Extension return string instead of html markup?
本文介绍了MVC HTML扩展返回的字符串,而不是HTML标记?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如果我有恩扩展这样的:
If I have en extension like that :
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"" /> ";
}
和我用它在这样的局部视图:
and I use it in a partial view like this :
@Html.ImageLink("../../Content/images/english.png","English", "ChangeCulture", "Account", new { lang = "en", returnUrl = this.Request.RawUrl }, null,null)
我有一个这样的输出:
I have an output like this :
任何想法,为什么?
推荐答案
之所以出现这种情况是因为 @
运营商剃刀自动HTML EN codeS。如果你想避免这种编码,你需要使用 IHtmlString
:
The reason this happens is because the @
operator in Razor automatically HTML encodes. If you want to avoid this encoding you need to use an 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"" />");
}
这显然会更正确的(和工作在所有情况下,无论从哪里,这个助手是如何调用物质),如果这样写的:
which obviously will be far more correct (and working in all situations, no matter from where and how this helper is called) if written like this:
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
:
As an alternative if you cannot modify the helper you could use @Html.Raw
:
@Html.Raw(Html.ImageLink("../../Content/images/english.png","English", "ChangeCulture", "Account", new { lang = "en", returnUrl = this.Request.RawUrl }, null,null))
这篇关于MVC HTML扩展返回的字符串,而不是HTML标记?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文