Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I show a viewbag as 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!

like image 284
David Archer Avatar asked Sep 02 '11 15:09

David Archer


People also ask

How do you access the ViewBag in HTML?

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.

Can we access ViewBag in JavaScript?

The ViewBag object value will be set inside Controller and then the value of the ViewBag object will be accessed inside JavaScript function using Razor syntax in ASP.Net MVC Razor.

Can we use ViewBag in layout page?

Simply use the viewbag in your home controller and you can also access it on the Layout page too.


1 Answers

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.

like image 156
KallDrexx Avatar answered Sep 24 '22 01:09

KallDrexx