34

I'm using the following to make the text output the line breaks entered in a <textarea> HTML element.

MvcHtmlString.Create(Model.Post.Description.Replace(Environment.NewLine, "<br />"))

Is there a nicer way to do this?

Leniel Maccaferri
  • 100,159
  • 46
  • 371
  • 480
raklos
  • 28,027
  • 60
  • 183
  • 301
  • I don't really see how this helper outputs any line breaks as you are replacing line breaks with a space. – Darin Dimitrov Mar 11 '11 at 18:12
  • @Darin - poor copy/pasting on my part, updated. – raklos Mar 11 '11 at 18:14
  • dup http://stackoverflow.com/questions/5032097/asp-net-mvc-convert-n-new-line-to-html-breaks – BlackTigerX Mar 11 '11 at 18:24
  • 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:54

7 Answers7

103

There's an even better/awesome solution that employs CSS white-space property:

Using this you avoid Cross-site scripting (XSS) vulnerabilities...

<p style="white-space: pre-line">@Model.Message</p>

Works like a charm with ASP.NET MVC Razor engine.

Leniel Maccaferri
  • 100,159
  • 46
  • 371
  • 480
24

Your code is vulnerable to XSS attacks as it doesn't HTML encode the text. I would recommend you the following:

var result = string.Join(
    "<br/>",
    Model.Post.Description
        .Split(new[] { Environment.NewLine }, StringSplitOptions.None)
        .Select(x => HttpUtility.HtmlEncode(x))
);
return MvcHtmlString.Create(result);

and then in your view you can safely:

@Html.SomeHelper()
Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928
6

Maybe you can output the text inside a <pre> tag.

willvv
  • 8,439
  • 16
  • 66
  • 101
5

Just use a tag. <pre>@Model.Post.Description</pre>

Or

@Html.Raw(HttpUtility.HtmlDecode(Model.Post.Description.Replace("\r\n", "<br>")))
Abhishek Kanrar
  • 418
  • 4
  • 6
0

It's working for me.

<p class="message">
@Html.Raw("<p>" + Model.Text + "</p>")
</p>

string Model.Text having < br/> tag inside.

Nalan Madheswaran
  • 10,136
  • 1
  • 57
  • 42
0

Here is my solution.

@MvcHtmlString.Create(Regex.Replace(Html.Encode(Model.Address), Environment.NewLine, "<br />", RegexOptions.Multiline))

and of course, you will have to add following using statement for Regex to work.

@using System.Text.RegularExpressions

Hope it is useful for someone.

Sikandar Amla
  • 1,415
  • 18
  • 27
0

Just do the following command as it has filtering enabled:

<p style="white-space: pre-line" <p>