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

 ̄綄美尐妖づ 提交于 2019-11-28 21:09:25

The following class implements a HtmlHelper that properly encodes the text:

public static class HtmlExtensions
{
    public static MvcHtmlString Nl2Br(this HtmlHelper htmlHelper, string text)
    {
        if (string.IsNullOrEmpty(text))
            return MvcHtmlString.Create(text);
        else
        {
            StringBuilder builder = new StringBuilder();
            string[] lines = text.Split('\n');
            for (int i = 0; i < lines.Length; i++)
            {
                if (i > 0)
                    builder.Append("<br/>\n");
                builder.Append(HttpUtility.HtmlEncode(lines[i]));
            }
            return MvcHtmlString.Create(builder.ToString());
        }
    }
}

It's easy to use in your views:

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

Or with Razor:

@Html.Nl2Br(Model.MultilineText)
mkataja

For a slightly different (and, IMHO, better and safer) way of solving the problem, see this answer to a similar question.

Basically, instead of going through the trouble of converting all new line characters to <br> elements, it is as simple as applying the following CSS to the element where you are showing the inputted text:

white-space: pre-line

You should always encode user entered text when displaying it back in the view to ensure that it is safe.

You could do as Cybernate suggested or could add it to a HtmlHelper extension method

public static string EncodedMultiLineText(this HtmlHelper helper, string text) {
  if (String.IsNullOrEmpty(text)) {
    return String.Empty;
  }
  return Regex.Replace(helper.Encode(text), Environment.NewLine, "<br/>")
}

So that it can be easily reused in you view

<%= Html.EncodedMultiLineText(Model.Description) %>

Try something like this:

<%=
Regex.Replace(
              Html.Encode(Model.Description), 
              Environment.NewLine, 
              "<br/>", 
              RegexOptions.IgnoreCase||RegexOptions.Multiline
             )
%>

The answer above that provides a static HTML helper extension provides an obsolete constructor:

return new MvcHtmlString(builder.ToString());

This line can be replaced by the following line of code:

return MvcHtmlString.Create((builder.ToString()));
Raúl Otaño

I think this answer solves the problems in a nice way, just using css: style="white-space: pre-line" check also: CSS white space property.

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

Use

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

Or

@Html.MultiLineText(Model.MultilineText)

For Asp.net mvc razor,i used Html.Encode for blocking xss attacks

@Html.Raw(Html.Encode(Model.Description).Replace(Environment.NewLine, "<br />"))
alexl

Maybe it's the answer: How do you handle line breaks in HTML Encoded MVC view?

or

you can try:

Model.Description.Replace(Environment.NewLine, "<br/>");

This works for me -

<%= HttpUtility.HtmlDecode(Html.ActionLink("AOT <br/> Claim #", "actionName" ))%>

It doesn't look like you're trying to HTML Encode so a regular replace should work fine.

<%= Model.Description.Replace(Environment.NewLine, "<br />")%>
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!