display line breaks asp.net mvc razor

2020-02-08 11:02发布

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?

6条回答
爷的心禁止访问
2楼-- · 2020-02-08 11:45

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

查看更多
孤傲高冷的网名
3楼-- · 2020-02-08 11:45

It's working for me.

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

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

查看更多
相关推荐>>
4楼-- · 2020-02-08 12:03

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()
查看更多
够拽才男人
5楼-- · 2020-02-08 12:04

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

Or

@Html.Raw(HttpUtility.HtmlDecode(Model.Post.Description.Replace("\r\n", "<br>")))
查看更多
家丑人穷心不美
6楼-- · 2020-02-08 12:05

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.

查看更多
\"骚年 ilove
7楼-- · 2020-02-08 12:08

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.

查看更多
登录 后发表回答