HTML.Encode but preserve line breaks

ⅰ亾dé卋堺 提交于 2019-12-02 20:09:27
Richard Schneider

Use HttpUtility.HtmlEncode then do the replace.

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

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.

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

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

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/>");

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/>"))
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!