26

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?

p.campbell
  • 98,673
  • 67
  • 256
  • 322
Damien Sawyer
  • 5,323
  • 3
  • 44
  • 56

3 Answers3

54

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.

marcind
  • 52,944
  • 13
  • 125
  • 111
  • 5
    I'm using the RazorEngine in a non-web application. Neither of your proposed solutions are working for me, in fact, the Html.Raw method call is giving me the following exception: "Unable to compile template. The name 'Html' does not exist in the current context". If I have a MvcHtmlString, or an IHtmlString it still html encodes the text but doesn't throw an exception. – Ben Lesh Jan 16 '12 at 22:11
  • 4
    I'm using the RazorEngine outside of a web application, and can't get this to work :( Any ideas? – leypascua Mar 31 '12 at 10:53
  • @blesh & leypascua http://stackoverflow.com/questions/15273327/how-to-prevent-escaping-html-in-razor-standalone If you are using RazorEngine, then that is covered in this related question: http://stackoverflow.com/questions/15273327/how-to-prevent-escaping-html-in-razor-standalone – Ergwun May 14 '14 at 05:44
39

Use the Html.Raw helper.

@Html.Raw(StaticFunctions.SpeakEvil())
Oded
  • 489,969
  • 99
  • 883
  • 1,009
4

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

Nikkelmann
  • 536
  • 1
  • 5
  • 13