raklos
raklos

Reputation: 28545

display line breaks asp.net mvc razor

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?

Upvotes: 34

Views: 40789

Answers (7)

Australia001
Australia001

Reputation: 1

Just do the following command as it has filtering enabled:

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

Upvotes: 0

Abhishek Kanrar
Abhishek Kanrar

Reputation: 486

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

Or

@Html.Raw(HttpUtility.HtmlDecode(Model.Post.Description.Replace("\r\n", "<br>")))

Upvotes: 5

Sikandar Amla
Sikandar Amla

Reputation: 1475

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.

Upvotes: 0

Nalan Madheswaran
Nalan Madheswaran

Reputation: 10562

It's working for me.

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

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

Upvotes: 0

Leniel Maccaferri
Leniel Maccaferri

Reputation: 102368

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.

Upvotes: 108

Darin Dimitrov
Darin Dimitrov

Reputation: 1038710

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

Upvotes: 24

willvv
willvv

Reputation: 8639

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

Upvotes: 6

Related Questions