Writing/outputting HTML strings unescaped
I've got safe/sanitized HTML saved in a DB table.
How can I have this HTML content written out in a Razor view?
It always escapes characters like <
and ampersands to &
.
Solution 1:
Supposing your content is inside a string named mystring
...
You can use:
@Html.Raw(mystring)
Alternatively you can convert your string to HtmlString
or any other type that implements IHtmlString
in model or directly inline and use regular @
:
@{ var myHtmlString = new HtmlString(mystring);}
@myHtmlString
Solution 2:
In ASP.NET MVC 3 You should do something like this:
// Say you have a bit of HTML like this in your controller:
ViewBag.Stuff = "<li>Menu</li>"
// Then you can do this in your view:
@MvcHtmlString.Create(ViewBag.Stuff)
Solution 3:
You can use
@{ WriteLiteral("html string"); }
Solution 4:
Sometimes it can be tricky to use raw html. Mostly because of XSS vulnerability. If that is a concern, but you still want to use raw html, you can encode the scary parts.
@Html.Raw("(<b>" + Html.Encode("<script>console.log('insert')</script>" + "Hello") + "</b>)")
Results in
(<b><script>console.log('insert')</script>Hello</b>)