HTML.Encode but preserve line breaks

前端 未结 5 1226
甜味超标
甜味超标 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:01

    If you find yourself using this more than once it may be helpful to wrap it in a custom HtmlHelper like this:

    namespace Helpers
    {
        public static class ExtensionMethods
        {
            public static IHtmlString PreserveNewLines(this HtmlHelper htmlHelper, string message)
            {
                return message == null ? null : htmlHelper.Raw(htmlHelper.Encode(message).Replace("\n", "<br/>"));
            }
        }
    }
    

    You'll then be able to use your custom HtmlHelper like this:

    @Html.PreserveNewLines(Message)
    

    Keep in mind that you'll need to add a using to your Helpers namespace for the HtmlHelper to be available.

    0 讨论(0)
  • 2021-02-01 14:14

    Use HttpUtility.HtmlEncode then do the replace.

    @Html.Raw(HttpUtility.HtmlEncode(Message).Replace("\n", "<br/>"))
    
    0 讨论(0)
  • 2021-02-01 14:17

    For those who use AntiXssEncoder.HtmlEncode

    As AntiXssEncoder.HtmlEncode encode the /r/n character to &#13;&#10; so the statement should be

    _mDraftMsgModel.wnItem.Description = AntiXssEncoder.HtmlEncode(draftModel.txtMsgContent, false).Replace("&#13;&#10;", "<br/>");
    
    0 讨论(0)
  • 2021-02-01 14:20

    You can encode your message, then display it raw. Something like:

    @Html.Raw(Server.HtmlEncode(Message).Replace("\n", "<br/>"))
    
    0 讨论(0)
  • 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("<br/>", "\n").Replace("<br />", "\n")).Replace("\n", "<br/>"))
    
    0 讨论(0)
提交回复
热议问题