Replace line break characters with <br /> in ASP.NET MVC Razor view
Solution 1:
Use the CSS white-space property instead of opening yourself up to XSS vulnerabilities!
<span style="white-space: pre-line">@Model.CommentText</span>
Solution 2:
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 />"))
Solution 3:
Split on newlines (environment agnostic) and print regularly -- no need to worry about encoding or xss:
@if (!string.IsNullOrWhiteSpace(text))
{
var lines = text.Split(new[] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries);
foreach (var line in lines)
{
<p>@line</p>
}
}
(remove empty entries is optional)