Search code examples
htmlstringasp.net-mvc-3

Getting HTML to recognize \n and \t


I have created a web application using ASP.NET MVC3, and want to display a string (that I constructed in the constructor) in a view. This string has \n and \t characters in it, and I want that formatting to remain in the view.

As of now, the view displays the string without any of the formatting, as if the \n and \t characters were never there. I checked my string by sending it to System.Diagnostics.Debug.Write, and in the output, the string appears as desired.

In the view, I am writing the string with

<p>@ViewBag.listItems</p>

(where listItems is the string mentioned). So, does anyone know how to force the view to display the string in the desired format? The string looks something like this:

"Title 1 + \n\t + subtitle1 + \n\t + subtitle2 + \n\t + \n + Title2 + \n\t + subtitle1"

Thanks!


Solution

  • Instead of the p tag, try using pre. Any text in this element displays in a fixed-width font and the text will retain formatting such as line breaks, and spaces, etc.

      <pre>@ViewBag.listItems</pre>