如何将 viewbag 显示为 html?
好的,对于 ASP.Net MVC 来说还很陌生,所以如果这是一个愚蠢的问题,我很抱歉,但是我该如何将 ViewBag 的值显示为 HTML。例如,如果 ViewBag.SomeMessage 包含以下文本:
测试 测试 测试 测试测试
我该如何让页面正常渲染HTML?或者有没有一种更简单的方法来实现这一点,但我完全错过了?
干杯!
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!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
![扫码二维码加入Web技术交流群](/public/img/jiaqun_03.jpg)
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
每个人使用
@Html.Raw()
都是正确的,但我想指出的是要小心这一点,因为它会使您的网站容易受到 XSS 漏洞的影响。我会将
@Html.Raw(ViewBag.SomeMessage)
与 结合起来Microsoft 的 Anti-XSS 库 确保您不会因此引入任何漏洞。编辑:
Anti-XSS 库的优点(如果您还没有看过它)是它有一个批准标记的白名单(例如
、
等..),以便只有批准的标记才会被取消编码。
编辑2:
这是一个示例 这是如何完成的。
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.
您可以使用
Raw
方法:You would use the
Raw
method:我认为你可以这样做:
I think you can do something like this:
话虽这么说,这是我的免责声明:不要使用 ViewBag。使用强类型视图和视图模型。 ViewBag/ViewData 对于 ASP.NET MVC 应用程序来说就像癌症。
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.
将数据作为 HTML 编码字符串放入 ViewBag,不应再次编码。
然后使用
文档 对于 MvcHtmlString。
put data to ViewBag as a HTML-encoded string that should not be encoded again.
then use
The documentation for MvcHtmlString.