Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

display line breaks asp.net mvc razor

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?

like image 560
raklos Avatar asked Mar 11 '11 18:03

raklos


2 Answers

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.

like image 76
Leniel Maccaferri Avatar answered Oct 11 '22 12:10

Leniel Maccaferri


Your code is vulnerable to XSS attacks as it doesn't HTML encode the text. I would recommend you the following:

var result = string.Join(     "<br/>",     Model.Post.Description         .Split(new[] { Environment.NewLine }, StringSplitOptions.None)         .Select(x => HttpUtility.HtmlEncode(x)) ); return MvcHtmlString.Create(result); 

and then in your view you can safely:

@Html.SomeHelper() 
like image 21
Darin Dimitrov Avatar answered Oct 11 '22 10:10

Darin Dimitrov