我一定是漏掉了什么,因为this doc
说,MvcHtmlString.Create("someStringHere")
返回 html 编码的字符串,但如果我有类似 MvcHtmlString.Create("<h1>myHeading</h1>")
的内容它仍然显示为
myHeading
(作为标题)而不是编码文本<h1>myHeading</h1>
那么声明是什么意思
MvcHtmlString.Create(String)
Creates an HTML-encoded string using the specified text value.
我无法理解,如果有人能解释文档的含义以及他们试图引用的编码与 html 编码之间的区别,我将不胜感激。
提前致谢!
最佳答案
我同意文档似乎误导了 MvcHtmlString
。
但是,MvcHtmlString
旨在用于当您不希望对字符串进行 HTML 编码时使用。 razor 的默认行为是对输出进行编码。
你传递给它的 Html 字符串应该已经被编码以确保它在没有额外编码的情况下输出。
假设以下 HTML 帮助器:
public static class HtmlHelper
{
public static string GetHtmlString(this System.Web.Mvc.HtmlHelper htmlHelper)
{
return "<h1>myHeading</h1>";
}
public static MvcHtmlString GetMvcHtmlString(this System.Web.Mvc.HtmlHelper htmlHelper)
{
return MvcHtmlString.Create("<h1>myHeading</h1>");
}
}
使用 Razor View :
@Html.GetHtmlString()
@Html.GetMvcHtmlString()
输出将是:
<h1>我的标题</h1>
我的标题
关于html - MvcHtmlString.Create() 方法不返回 Html 编码的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56075318/