33

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:

<%= Model.Description%>
Shawn Mclean
  • 56,733
  • 95
  • 279
  • 406
  • In one line. no `
    ` was created.
    – Shawn Mclean Feb 17 '11 at 17:10
  • 2
    Actually, the accepted answer here provides a much better implementation: http://stackoverflow.com/questions/4220381/replace-line-break-characters-with-br-in-asp-net-mvc-razor-view – Nullius Jul 12 '13 at 07:06
  • Does this answer your question? [Replace line break characters with
    in ASP.NET MVC Razor view](https://stackoverflow.com/questions/4220381/replace-line-break-characters-with-br-in-asp-net-mvc-razor-view)
    – avs099 Sep 28 '20 at 15:53

11 Answers11

51

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)
Codo
  • 75,595
  • 17
  • 168
  • 206
  • 15
    This HtmlExensions business is exactly what I was looking for. But, why not replace the whole body with `return MvcHtmlString.Create(HttpUtility.HtmlEncode(text).Replace("\n", "
    "));`?
    – Christopher Feb 21 '12 at 23:53
  • I'll let myself edit your answer to add text null reference check – horgh Oct 22 '12 at 02:47
  • why replace \n with br if you can keep the \n and just add the br it will be a lot easier to read in view:source , so basically going for \n br or br \n over just br in the end result – Michiel Cornille Jul 24 '14 at 12:57
  • This is the right way: http://stackoverflow.com/questions/4220381/replace-line-break-characters-with-br-in-asp-net-mvc-razor-view – Guido Zanon May 11 '15 at 13:40
  • 2
    Please show all imports/includes as MvcHtmlString does not exist by default. – rollsch Apr 17 '20 at 08:23
  • @rolls I haven't developed using ASP.NET MVC for a while and don't have a system anymore to check the imports. – Codo Apr 17 '20 at 12:40
28

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
Community
  • 1
  • 1
mkataja
  • 970
  • 2
  • 10
  • 28
  • 2
    I may be the only idiot who had this problem but to save the next person some time: if you do this, make sure you remove all extraneous line breaks inside your div. – Hugh Seagraves Mar 11 '19 at 16:20
  • This won't work in all mail clients. Use solution of @Codo – Flappy Sep 21 '20 at 07:37
11

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) %>
David Glenn
  • 24,412
  • 19
  • 74
  • 94
6

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

@Html.Raw(Html.Encode(Model.Description).Replace(Environment.NewLine, "<br />"))
İbrahim Özbölük
  • 3,162
  • 23
  • 20
6

Try something like this:

<%=
Regex.Replace(
              Html.Encode(Model.Description), 
              Environment.NewLine, 
              "<br/>", 
              RegexOptions.IgnoreCase||RegexOptions.Multiline
             )
%>
Chandu
  • 81,493
  • 19
  • 133
  • 134
5

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()));
Roland Schaer
  • 1,656
  • 1
  • 22
  • 30
4

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.

Community
  • 1
  • 1
Raúl Otaño
  • 4,640
  • 3
  • 31
  • 65
1

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/>");
Community
  • 1
  • 1
alexl
  • 6,841
  • 3
  • 24
  • 29
  • It's very dangerous to output user entered text that hasn't been encoded. Encoding should be encouraged even though it wasn't used in the original question. – David Glenn Feb 17 '11 at 18:13
1

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)
Alvis
  • 3,543
  • 5
  • 36
  • 41
0

This works for me -

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

Hemant Tank
  • 1,724
  • 4
  • 28
  • 56
-1

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

<%= Model.Description.Replace(Environment.NewLine, "<br />")%>
Nick Spiers
  • 2,344
  • 2
  • 19
  • 31
  • 1
    It's very dangerous to output user entered text that hasn't been encoded. Encoding should be encouraged even though it wasn't used in the original question. – David Glenn Feb 17 '11 at 18:13
  • You're right for the most part. I was under the assumption this wasn't an issue as OP wasn't encoding to begin with. OP never specified if it was an admin panel or if it was anonymous user input. If it's some sort of CMS system with only administrator access (probably a minority case), you wouldn't want to encode it. – Nick Spiers Feb 17 '11 at 18:50