display line breaks asp.net mvc razor

raklos picture raklos · Mar 11, 2011 · Viewed 31.7k times · Source

I'm using the following to make the text output the line breaks entered in a <textarea> HTML element.

MvcHtmlString.Create(Model.Post.Description.Replace(Environment.NewLine, "<br />"))

Is there a nicer way to do this?

Answer

Leniel Maccaferri picture Leniel Maccaferri · Jan 11, 2013

There's an even better/awesome solution that employs CSS white-space property:

Using this you avoid Cross-site scripting (XSS) vulnerabilities...

<p style="white-space: pre-line">@Model.Message</p>

Works like a charm with ASP.NET MVC Razor engine.