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 &
.
@Html.Raw()
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
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)
You can use
@{ WriteLiteral("html string"); }
Html.Raw()
doesn't work there
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>)
You can put your string into viewdata in controller like this :
ViewData["string"] = DBstring;
And then call that viewdata in view like this :
@Html.Raw(ViewData["string"].ToString())
Apart from using @MvcHtmlString.Create(ViewBag.Stuff)
as suggested by Dommer, I suggest you to also use AntiXSS library as suggested phill http://haacked.com/archive/2010/04/06/using-antixss-as-the-default-encoder-for-asp-net.aspx
It encodes almost all the possible XSS attack string.
Complete example for using template functions in RazorEngine (for email generation, for example):
@model SomeModel
@{
Func<PropertyChangeInfo, object> PropInfo =
@<tr class="property">
<td>
@item.PropertyName
</td>
<td class="value">
<small class="old">@item.OldValue</small>
<small class="new">@item.CurrentValue</small>
</td>
</tr>;
}
<body>
@{ WriteLiteral(PropInfo(new PropertyChangeInfo("p1", @Model.Id, 2)).ToString()); }
</body>
Success story sharing
razor
syntax andHtml.Raw
is definitely available to me.