Turn off HTML Encoding in Razor

╄→尐↘猪︶ㄣ 提交于 2019-11-30 22:29:50

问题


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

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

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

@StaticFunctions.SpeakEvil()

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


回答1:


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

For a helper like you have I would suggest returning an 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.




回答2:


Use the Html.Raw helper.

@Html.Raw(StaticFunctions.SpeakEvil())



回答3:


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

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



来源:https://stackoverflow.com/questions/4973504/turn-off-html-encoding-in-razor

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!