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?
Use the
Html.Raw
helper.Return a
MvcHtmlString
(Inherits fromHtmlString
) by calling theMvcHtmlString.Create()
method like so:You could also make it into an String extension:
Source:
http://geekswithblogs.net/shaunxu/archive/2010/04/10/lt-gt-htmlencode-ihtmlstring-and-mvchtmlstring.aspx
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
:That way you don't have have to call
Raw()
at every callsite.