Replace line break characters with <br /> in ASP.NET MVC Razor view
Use the CSS white-space property instead of opening yourself up to XSS vulnerabilities!
<span style="white-space: pre-line">@Model.CommentText</span>
Try the following:
@MvcHtmlString.Create(Model.CommentText.Replace(Environment.NewLine, "<br />"))
Update:
According to marcind's
comment on this related question, the ASP.NET MVC team is looking to implement something similar to the <%:
and <%=
for the Razor view engine.
Update 2:
We can turn any question about HTML encoding into a discussion on harmful user inputs, but enough of that already exists.
Anyway, take care of potential harmful user input.
@MvcHtmlString.Create(Html.Encode(Model.CommentText).Replace(Environment.NewLine, "<br />"))
Update 3 (Asp.Net MVC 3):
@Html.Raw(Html.Encode(Model.CommentText).Replace("\n", "<br />"))