How can I show a viewbag as html?

一世执手 提交于 2019-12-20 10:33:45

问题


OK, quite new to ASP.Net MVC, so I'm sorry if this is a silly question, but how do I go about showing the values of a ViewBag as HTML. For Example, if ViewBag.SomeMessage contains the following text:

<h3>Test</h3><p>Test</p><p>Test</p><p>Test</p><p>Test</p><p>TEST</p>

How would I go about actually having the page render that as normal HTML? Or is there a much easier way of achieving this that I'm totally missing?

Cheers!


回答1:


Everyone is correct in the use of @Html.Raw() but I want to point out to be careful with this, as it can make your site susceptible to XSS vulnerabilities.

I would combine the @Html.Raw(ViewBag.SomeMessage) with Microsoft's Anti-XSS Library to make sure you do not introduce any vulnerabilities from this.

Edit: The advantage of the Anti-XSS library (if you haven't looked at it) is it has a whitelist of approved markups (such as <b>, <h3>, etc..) so that only approved markups will be un-encoded.

Edit2: Here's an example of how this is done.




回答2:


You would use the Raw method:

 @Html.Raw(ViewBag.SomeMessage)



回答3:


I think you can do something like this:

@Html.Raw(ViewBag.SomeMessage)



回答4:


@Html.Raw(ViewBag.SomeHtmlProperty)

This being said, here's my disclaimer: DON'T USE ViewBag. Use strongly typed views and view models. ViewBag/ViewData is like cancer for an ASP.NET MVC application.




回答5:


put data to ViewBag as a HTML-encoded string that should not be encoded again.

ViewBag.myBag = MvcHtmlString.Create(myCode ?? string.Empty);

then use

@ViewBag.myBag

The documentation for MvcHtmlString.



来源:https://stackoverflow.com/questions/7285790/how-can-i-show-a-viewbag-as-html

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!