[英]Why custom html helper doesn't render tag properly
I made my html helper method 我做了我的HTML辅助方法
public static string MedalImage(this HtmlHelper helper, Color color)
{
var builder = new TagBuilder("img");
switch (color)
{
case Color.Blue:
builder.MergeAttribute("src", "/Content/Medals/blueMedal.png");
break;
default:
builder.MergeAttribute("src", "/Content/Medals/redMedal.png");
break;
}
builder.MergeAttribute("alt", "Image not found");
return builder.ToString(TagRenderMode.SelfClosing);
}
But when I want to use it in View like this @Html.MedalImage(HtmlHelpers.Color.Red)
then it renders: 但是当我想在View中像这样
@Html.MedalImage(HtmlHelpers.Color.Red)
使用它时,它将呈现:
<img alt="Image not found" src="/Content/Medals/redMedal.png" />
And in this case it does not make image, only text. 在这种情况下,它不会生成图像,而只会生成文本。
But when I use @Html.Raw(Html.MedalImage(HtmlHelpers.Color.Red))
it does work as expected and renders my image. 但是当我使用
@Html.Raw(Html.MedalImage(HtmlHelpers.Color.Red))
它确实可以正常工作并呈现我的图像。 Can someone tell me why? 有人可以告诉我为什么吗? Or how to fix my helper so I don't have to use Html.Raw method?
或者如何修复我的助手,这样我就不必使用Html.Raw方法?
The standard behaviour of MVC Razor is to HTML-encode every string. MVC Razor的标准行为是对每个字符串进行HTML编码。 The only time it will not do so is if the object is an
IHtmlString
, which is little more than a wrapper interface for strings. 唯一不会这样做的时间是,如果对象是
IHtmlString
,它仅是字符串的包装器接口。
By wrapping your string as an IHtmlString
, Razor will treat it as 'already encoded' and 'ready to be sent as-is'. 通过将字符串包装为
IHtmlString
,Razor会将其视为“已编码”和“准备按原样发送”。 There are at least two ways to do this: 至少有两种方法可以执行此操作:
var htmlStr1 = new HtmlString(myStringThatContainsHtml);
var htmlStr2 = new MvcHtmlString(myStringThatContainsHtml);
or applied to your code: 或应用于您的代码:
return new HtmlString(builder.ToString(TagRenderMode.SelfClosing));
return new MvcHtmlString(builder.ToString(TagRenderMode.SelfClosing));
And then your method signature needs to be changed: 然后需要更改您的方法签名:
public static IHtmlString MedalImage(...) { ... }
The reason that there are two ways is historic. 有两种方式的原因是历史性的。 MVC2 did not have the IHtmlString interface, and it had only the MvcHtmlString class.
MVC2没有IHtmlString接口,只有MvcHtmlString类。 From MVC3 the IHtmlString interface was created and also the class HtmlString, and MvcHtmlString now inherits from HtmlString.
从MVC3创建了IHtmlString接口,并且还创建了类HtmlString和MvcHtmlString现在从HtmlString继承。 For more on that, see HtmlString vs. MvcHtmlString .
有关更多信息,请参见HtmlString与MvcHtmlString 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.