Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Turn off HTML Encoding in Razor

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?

like image 215
Damien Sawyer Avatar asked Feb 11 '11 20:02

Damien Sawyer


2 Answers

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.

like image 154
marcind Avatar answered Sep 20 '22 15:09

marcind


Use the Html.Raw helper.

@Html.Raw(StaticFunctions.SpeakEvil()) 
like image 27
Oded Avatar answered Sep 16 '22 15:09

Oded