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.
In my case, my string contained html that I wanted to encode but I also wanted the HTML line breaks to remain in place. The code below turns the HTML line breaks in to \n then encodes everything. It then turns all instances of \n back in to HTML line breaks:
@Html.Raw(HttpUtility.HtmlEncode(message.Replace("
", "\n").Replace("
", "\n")).Replace("\n", "
"))