asp.net-mvc 在 ASP.NET MVC Razor 视图中用 <br /> 替换换行符

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4220381/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 00:35:45  来源:igfitidea点击:

Replace line break characters with <br /> in ASP.NET MVC Razor view

asp.net-mvcasp.net-mvc-3razor

提问by bkaid

I have a textarea control that accepts input. I am trying to later render that text to a view by simply using:

我有一个接受输入的 textarea 控件。我稍后会尝试通过简单地使用以下方法将该文本呈现到视图中:

@Model.CommentText

@Model.CommentText

This is properly encoding any values. However, I want to replace the line break characters with <br />and I can't find a way to make sure that the new br tags don't get encoded. I have tried using HtmlString but haven't had any luck yet.

这是正确编码任何值。但是,我想用 替换换行符,<br />但找不到确保新 br 标签不被编码的方法。我曾尝试使用 HtmlString 但还没有任何运气。

回答by Jacob Krall

Use the CSS white-space propertyinstead of opening yourself up to XSS vulnerabilities!

使用CSS 空白属性而不是让自己暴露在 XSS 漏洞面前!

<span style="white-space: pre-line">@Model.CommentText</span>

回答by Omar

Try the following:

请尝试以下操作:

@MvcHtmlString.Create(Model.CommentText.Replace(Environment.NewLine, "<br />"))

Update:

更新:

According to marcind'scomment on this related question, the ASP.NET MVC team is looking to implement something similar to the <%:and <%=for the Razor view engine.

根据marcind's对此相关问题的评论,ASP.NET MVC 团队正在寻求为 Razor 视图引擎实现类似于<%:和 的东西<%=

Update 2:

更新 2:

We can turn any question about HTML encoding into a discussion on harmful user inputs, but enough of that already exists.

我们可以将任何关于 HTML 编码的问题转化为关于有害用户输入的讨论,但已经存在的足够多。

Anyway, take care of potential harmful user input.

无论如何,请注意潜在的有害用户输入。

@MvcHtmlString.Create(Html.Encode(Model.CommentText).Replace(Environment.NewLine, "<br />"))

Update 3 (Asp.Net MVC 3):

更新 3(Asp.Net MVC 3):

@Html.Raw(Html.Encode(Model.CommentText).Replace("\n", "<br />"))

回答by drzaus

Split on newlines (environment agnostic) and print regularly -- no need to worry about encoding or xss:

拆分换行符(与环境无关)并定期打印——无需担心编码或 xss:

@if (!string.IsNullOrWhiteSpace(text)) 
{
    var lines = text.Split(new[] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries);
    foreach (var line in lines)
    {
        <p>@line</p>
    }
}

(remove empty entries is optional)

(删除空条目是可选的)

回答by thelem

Omar's third solution as an HTML Helper would be:

Omar 作为 HTML Helper 的第三个解决方案是:

public static IHtmlString FormatNewLines(this HtmlHelper helper, string input)
{
    return helper.Raw(helper.Encode(input).Replace("\n", "<br />"));
}

回答by Akaoni

Applying the DRY principleto Omar's solution, here's an HTML Helper extension:

DRY 原则应用于 Omar 的解决方案,这是一个 HTML Helper 扩展:

using System.Web.Mvc;
using System.Text.RegularExpressions;

namespace System.Web.Mvc.Html {
    public static class MyHtmlHelpers {
        public static MvcHtmlString EncodedReplace(this HtmlHelper helper, string input, string pattern, string replacement) {
            return new MvcHtmlString(Regex.Replace(helper.Encode(input), pattern, replacement));
        }
    }
}

Usage (with improved regex):

用法(使用改进的正则表达式):

@Html.EncodedReplace(Model.CommentText, "[\n\r]+", "<br />")

This also has the added benefit of putting less onus on the Razor View developer to ensure security from XSS vulnerabilities.

这还有一个额外的好处,即减少了 Razor View 开发人员在确保 XSS 漏洞的安全性方面的责任。



My concern with Jacob's solution is that rendering the line breaks with CSS breaks the HTML semantics.

我对 Jacob 的解决方案的担忧是,使用 CSS 渲染换行符会破坏HTML 语义

回答by Andrea

I needed to break some text into paragraphs ("p" tags), so I created a simple helper using some of the recommendations in previous answers (thank you guys).

我需要将一些文本分成段落(“p”标签),因此我使用之前答案中的一些建议创建了一个简单的帮助程序(谢谢大家)。

public static MvcHtmlString ToParagraphs(this HtmlHelper html, string value) 
    { 
        value = html.Encode(value).Replace("\r", String.Empty);
        var arr = value.Split('\n').Where(a => a.Trim() != string.Empty);
        var htmlStr = "<p>" + String.Join("</p><p>", arr) + "</p>";
        return MvcHtmlString.Create(htmlStr);
    }

Usage:

用法:

@Html.ToParagraphs(Model.Comments)

回答by James S.

I prefer this method as it doesn't require manually emitting markup. I use this because I'm rendering Razor Pages to strings and sending them out via email, which is an environment where the white-space styling won't always work.

我更喜欢这种方法,因为它不需要手动发出标记。我使用它是因为我将 Razor Pages 渲染为字符串并通过电子邮件将它们发送出去,在这种环境中,空白样式并不总是有效。

public static IHtmlContent RenderNewlines<TModel>(this IHtmlHelper<TModel> html, string content)
{
    if (string.IsNullOrEmpty(content) || html is null)
    {
        return null;
    }

    TagBuilder brTag = new TagBuilder("br");
    IHtmlContent br = brTag.RenderSelfClosingTag();
    HtmlContentBuilder htmlContent = new HtmlContentBuilder();

    // JAS: On the off chance a browser is using LF instead of CRLF we strip out CR before splitting on LF.
    string lfContent = content.Replace("\r", string.Empty, StringComparison.InvariantCulture);
    string[] lines = lfContent.Split('\n', StringSplitOptions.None);
    foreach(string line in lines)
    {
        _ = htmlContent.Append(line);
        _ = htmlContent.AppendHtml(br);
    }

    return htmlContent;
}