asp.net mvc convert \n new line to html breaks

前端 未结 11 598
逝去的感伤
逝去的感伤 2020-12-14 15:10

I have a textarea in mvc. When data is entered into that and I\'m displaying it back to the user, how do I show the line breaks?

I display like this:

11条回答
  •  粉色の甜心
    2020-12-14 16:04

    I like using HtmlExtensions, Environment.NewLine and Regex, which were in different answers, so I kinda put the above answers into a single method.

    public static MvcHtmlString MultiLineText(this HtmlHelper htmlHelper, string text) {
     if (string.IsNullOrEmpty(text)) {
         return MvcHtmlString.Create(string.Empty);
     }
     return MvcHtmlString.Create(Regex.Replace(HttpUtility.HtmlEncode(text), Environment.NewLine, "
    ")); }

    Use

    <%= Html.MultiLineText(Model.MultilineText) %>
    

    Or

    @Html.MultiLineText(Model.MultilineText)
    

提交回复
热议问题