34

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%>
3

11 Answers 11

52

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)
Sign up to request clarification or add additional context in comments.

6 Comments

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", "<br />"));?
I'll let myself edit your answer to add text null reference check
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
Please show all imports/includes as MvcHtmlString does not exist by default.
|
30

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

2 Comments

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.
This won't work in all mail clients. Use solution of @Codo
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) %>

1 Comment

Apologies for encouraging encoding in my comment and then missing it out in my own code. Fail.
7

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

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

Comments

6

Try something like this:

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

3 Comments

why did this one get the most votes? Is it the most efficient or most secure?
It may have had some advantage being the oldest.
You should not use Regex.Replace here.
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()));

3 Comments

Found another issue with the example. It break on a null input. Can be fixed by inserting the following code on the first line of the method: if(text == null) return MvcHtmlString.Create(text);
Thanks alot for this. I never knew it would break.
Thanks for up vote. I can now add comments instead having to post these silly fragments as answers.
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.

Comments

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

1 Comment

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.
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)

Comments

0

This works for me -

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

Comments

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

2 Comments

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.
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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.