How can I show a viewbag as html?
Asked Answered
N

5

30

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!

Nutlet answered 2/9, 2011 at 15:32 Comment(0)
M
62

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.

Mesotron answered 2/9, 2011 at 15:38 Comment(2)
shameless self promotion on what xss is and using anti-xss, plus other hack proofing stuff: channel9.msdn.com/Events/TechEd/NorthAmerica/2011/DEV333Marmoset
As far as the Anti-XSS library is concerned, are you saying there is a way to implement it that will change the behavior of Html.Raw to do what you outlined, or are you stating to use it with Html.Raw in order to be safe?Napery
N
19

You would use the Raw method:

 @Html.Raw(ViewBag.SomeMessage)
Nakashima answered 2/9, 2011 at 15:34 Comment(0)
A
9

I think you can do something like this:

@Html.Raw(ViewBag.SomeMessage)
Arius answered 2/9, 2011 at 15:34 Comment(0)
T
8
@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.

Theurgy answered 2/9, 2011 at 15:34 Comment(1)
Why? Please explain. Why is ViewBag "like cancer"?Clemenciaclemency
G
3

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.

Gizzard answered 15/12, 2016 at 13:45 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.