Text output from MVC ViewBag with some areas not encoded?

Consider the following example:

<div>@ViewBag.MyData</div> 

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

How to help me?

+6
source share
3 answers

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

+13
source

the following will do what you need ...

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

The Create method will accept the HTML string and display it as expected if you just typed the HTML right on the page

+5
source

Something that html pre tag is used for

pre> defines preformatted text. The text in <pre> is displayed in a fixed-width font (usually Courier), and it saves both spaces and line breaks ...

And in the razor pattern

 < pre>@ViewBag.MyData</ pre> 
+2
source

Source: https://habr.com/ru/post/904313/


All Articles