HTML.Encode but preserve line breaks

前端 未结 5 1263
甜味超标
甜味超标 2021-02-01 13:48

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.         


        
5条回答
  •  暗喜
    暗喜 (楼主)
    2021-02-01 14:23

    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", "
    "))

提交回复
热议问题