Writing/outputting HTML strings unescaped

2019-01-02 17:00发布

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

6条回答
何处买醉
2楼-- · 2019-01-02 17:29

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())
查看更多
查无此人
3楼-- · 2019-01-02 17:38

You can use

@{ WriteLiteral("html string"); }
查看更多
君临天下
4楼-- · 2019-01-02 17:41

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
查看更多
浅入江南
5楼-- · 2019-01-02 17:41

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)
查看更多
高级女魔头
6楼-- · 2019-01-02 17:43

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.

查看更多
泪湿衣
7楼-- · 2019-01-02 17:53

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>)
查看更多
登录 后发表回答