gpt4 book ai didi

c# - MVC Html 扩展返回字符串而不是 html 标记?

转载 作者:IT王子 更新时间:2023-10-29 04:52:02 25 4
gpt4 key购买 nike

如果我有这样的扩展名:

 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"" /> ";
}

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

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

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

知道为什么吗?

最佳答案

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

关于c# - MVC Html 扩展返回字符串而不是 html 标记?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5888864/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com