asp.net-mvc 在 Razor 中关闭 HTML 编码

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4973504/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 00:52:51  来源:igfitidea点击:

Turn off HTML Encoding in Razor

asp.net-mvcrazorhtml-encode

提问by Damien Sawyer

I have a function that returns a snippet of JavaScript and/or HTML.

我有一个返回 JavaScript 和/或 HTML 片段的函数。

static public string SpeakEvil()
{
    return "<script>alert('BLAH!!');</script>";
}

In the view, Razor is quite rightly HTML encoding it, as most would expect.

在这个观点中,正如大多数人所期望的那样,Razor 是非常正确的 HTML 编码。

@StaticFunctions.SpeakEvil()

How do I have Razor notHTML Encode this, so that the HTML and JavaScript are emitted verbatim, and that any script actually runs?

我如何让 Razor而不是HTML 编码,以便逐字发送 HTML 和 JavaScript,并且任何脚本实际运行?

回答by marcind

You could use the Raw()function but it's mostly meant for things that come from the database.

您可以使用该Raw()函数,但它主要用于来自数据库的内容。

For a helper like you have I would suggest returning an IHtmlString:

对于像您这样的帮手,我建议返回一个IHtmlString

static public IHtmlString SpeakEvil() {
    return new HtmlString("<script>alert('BLAH!!');</script>");
}

That way you don't have have to call Raw()at every callsite.

这样您就不必Raw()在每个呼叫站点都进行呼叫。

回答by Oded

Use the Html.Rawhelper.

使用Html.Raw帮手。

@Html.Raw(StaticFunctions.SpeakEvil())

回答by Nikkelmann

Return a MvcHtmlString(Inherits from HtmlString) by calling the MvcHtmlString.Create()method like so:

通过调用方法返回 a MvcHtmlString(Inherits from HtmlString),MvcHtmlString.Create()如下所示:

public static MvcHtmlString SpeakEvil()
{
    return MvcHtmlString.Create("<script>alert('BLAH!!');</script>");
}


You could also make it into an String extension:


你也可以把它变成一个字符串扩展:

public static MvcHtmlString HtmlSafe(this string content)
{
    return MvcHtmlString.Create(content);
}


Source:
http://geekswithblogs.net/shaunxu/archive/2010/04/10/lt-gt-htmlencode-ihtmlstring-and-mvchtmlstring.aspx


来源:http:
//geekswithblogs.net/shaunxu/archive/2010/04/10/lt-gt-htmlencode-ihtmlstring-and-mvchtmlstring.aspx