Reputation: 4653
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 &
.
Upvotes: 462
Views: 310614
Reputation: 730
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>
Upvotes: 0
Reputation: 29427
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
Upvotes: 689
Reputation: 82287
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>)
Upvotes: 10
Reputation: 317
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())
Upvotes: 5
Reputation: 1658
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.
Upvotes: 2
Reputation: 14941
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)
Upvotes: 76