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?
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.
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.
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.
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.
Use HttpUtility.HtmlEncode then do the replace.
@Html.Raw(HttpUtility.HtmlEncode(Message).Replace("\n", "<br/>"))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With