Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Outputting MVC ViewBag text with some areas not encoded?

Tags:

c#

asp.net-mvc

Consider the following example:

<div>@ViewBag.MyData</div>

What to do if ViewBag.MyData contains a string with "\n" (newlines) in it, that I want to change into "<br/>"? When I include "<br/>" instead of the newlines, it gets encoded in the browser, which is bad.

How can I help this?

like image 937
Mathias Lykkegaard Lorenzen Avatar asked Dec 22 '11 13:12

Mathias Lykkegaard Lorenzen


2 Answers

use @Html.Raw(ViewBag.MyData.Replace("\n", "</br>"))

like image 102
davethecoder Avatar answered Nov 14 '22 21:11

davethecoder


the following will do what you need...

@MvcHtmlString.Create(ViewBag.MyData.Replace("\n", "</br>"))

The Create method will take a HTML string and render it as would be expected if you just typed the HTML straight onto the page

like image 25
musefan Avatar answered Nov 14 '22 21:11

musefan