Search code examples
asp.net-mvcasp.net-mvc-3html-encode

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?


Solution

  • Use HttpUtility.HtmlEncode then do the replace.

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