display line breaks asp.net mvc razor
Asked Answered
A

7

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?

Amendatory answered 11/3, 2011 at 18:10 Comment(4)
I don't really see how this helper outputs any line breaks as you are replacing line breaks with a space.Mosera
@Darin - poor copy/pasting on my part, updated.Amendatory
dup #5032597Pignus
Does this answer your question? Replace line break characters with <br /> in ASP.NET MVC Razor viewRadie
H
107

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.

Hiltan answered 11/1, 2013 at 2:2 Comment(1)
This should be in fact the accepted answer. Because the op ask for a nicer way !Grange
M
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()
Mosera answered 11/3, 2011 at 18:17 Comment(0)
N
6

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

Nisus answered 11/3, 2011 at 18:13 Comment(1)
simple but working, thanks a lotVacuous
N
5

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

Or

@Html.Raw(HttpUtility.HtmlDecode(Model.Post.Description.Replace("\r\n", "<br>")))
Neumeyer answered 23/1, 2019 at 5:51 Comment(0)
M
0

It's working for me.

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

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

Mariel answered 25/2, 2013 at 18:25 Comment(2)
That is open to XSS attack. Place <script>alert('XSS')'</script> into you Model.Text and you have a vuln.Hodges
@Hodges then come with a better solutionLaw
M
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.

Miscalculate answered 28/3, 2017 at 9:47 Comment(0)
U
0

Just do the following command as it has filtering enabled:

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

Upali answered 24/3, 2021 at 1:56 Comment(1)
How is this different form the accepted answer?Overexcite

© 2022 - 2024 — McMap. All rights reserved.