如何将 viewbag 显示为 html?

发布于 2024-12-02 23:14:39 字数 267 浏览 2 评论 0原文

好的,对于 ASP.Net MVC 来说还很陌生,所以如果这是一个愚蠢的问题,我很抱歉,但是我该如何将 ViewBag 的值显示为 HTML。例如,如果 ViewBag.SomeMessage 包含以下文本:

测试

测试

测试

测试

测试

< p>TEST

我该如何让页面正常渲染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技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

旧时光的容颜 2024-12-09 23:14:39

每个人使用 @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.

静待花开 2024-12-09 23:14:39

您可以使用 Raw 方法:

 @Html.Raw(ViewBag.SomeMessage)

You would use the Raw method:

 @Html.Raw(ViewBag.SomeMessage)
娇纵 2024-12-09 23:14:39

我认为你可以这样做:

@Html.Raw(ViewBag.SomeMessage)

I think you can do something like this:

@Html.Raw(ViewBag.SomeMessage)
茶花眉 2024-12-09 23:14:39
@Html.Raw(ViewBag.SomeHtmlProperty)

话虽这么说,这是我的免责声明:不要使用 ViewBag。使用强类型视图和视图模型。 ViewBag/ViewData 对于 ASP.NET MVC 应用程序来说就像癌症。

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

聊慰 2024-12-09 23:14:39

将数据作为 HTML 编码字符串放入 ViewBag,不应再次编码。

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

然后使用

@ViewBag.myBag

文档 对于 MvcHtmlString。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文