Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HTML.Encode but preserve line breaks

I take user input into a text area, store it and eventually display it back to the user.

In my View (Razor) I want to do something like this...

@Message.Replace("\n", "</br>") 

This doesn't work because Razor Html Encodes by default. This is great but I want my line breaks.

If I do this I get opened up to XSS problems.

@Html.Raw(Message.Replace("\n", "</br>")) 

What's the right way to handle this situation?

like image 689
BZink Avatar asked Apr 06 '11 01:04

BZink


People also ask

How do you keep a line break in HTML?

The <pre> tag defines preformatted text. Text in a <pre> element is displayed in a fixed-width font, and the text preserves both spaces and line breaks. The text will be displayed exactly as written in the HTML source code.

How do I preserve line breaks when getting text from a textarea?

To preserve line breaks when getting text from a textarea with JavaScript, we can replace whitespace characters with '<br>\n' . const post = document. createElement("p"); post. textContent = postText; post.

How do I print text on the next line in HTML?

In HTML, the <br> element creates a line break. You can add it wherever you want text to end on the current line and resume on the next.

What is HtmlEncode asp net?

HtmlEncode is a convenient way to access the HttpUtility. HtmlEncode method at run time from an ASP.NET application. Internally, HtmlEncode uses HttpUtility. HtmlEncode to encode strings. To encode or decode values outside of a web application, use the WebUtility class.


1 Answers

Use HttpUtility.HtmlEncode then do the replace.

@Html.Raw(HttpUtility.HtmlEncode(Message).Replace("\n", "<br/>")) 
like image 57
Richard Schneider Avatar answered Oct 05 '22 23:10

Richard Schneider