HTML.Encode but preserve line breaks

BZink picture BZink · Apr 6, 2011 · Viewed 34.7k times · Source

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?

Answer

Richard Schneider picture Richard Schneider · Apr 6, 2011

Use HttpUtility.HtmlEncode then do the replace.

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