AGS
AGS

Reputation: 4653

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 &amp;.

Upvotes: 462

Views: 310614

Answers (7)

ZlobnyiSerg
ZlobnyiSerg

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

Lorenzo
Lorenzo

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

Travis J
Travis J

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>&lt;script&gt;console.log('insert')&lt;/script&gt;Hello</b>)

Upvotes: 10

Ajay
Ajay

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

Andrus
Andrus

Reputation: 27931

You can use

@{ WriteLiteral("html string"); }

Upvotes: 76

ZeNo
ZeNo

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

Tom Chantler
Tom Chantler

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

Related Questions