首页 文章

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

提问于
浏览
224

我有一个接受输入的textarea控件 . 我想稍后通过简单地使用以下方法将该文本呈现给视图:

@ Model.CommentText

这适当地编码任何值 . 但是,我想用
替换换行符,我可以't find a way to make sure that the new br tags don'得到编码 . 我尝试过使用HtmlString,但还没有运气 .

6 回答

  • 105

    使用CSS white-space property而不是打开自己的XSS漏洞!

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

    请尝试以下方法:

    @MvcHtmlString.Create(Model.CommentText.Replace(Environment.NewLine, "
    "))

    更新:

    根据this related questionthis related question的评论,ASP.NET MVC团队正在寻求为Razor视图引擎实现类似于 <%:<%= 的东西 .

    更新2:

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

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

    @MvcHtmlString.Create(Html.Encode(Model.CommentText).Replace(Environment.NewLine, "
    "))

    更新3(Asp.Net MVC 3):

    @Html.Raw(Html.Encode(Model.CommentText).Replace("\n", "
    "))
  • 4

    拆分换行符(环境不可知)并定期打印 - 无需担心编码或xss:

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

    (删除空条目是可选的)

  • 8

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

    public static IHtmlString FormatNewLines(this HtmlHelper helper, string input)
    {
        return helper.Raw(helper.Encode(input).Replace("\n", "
    ")); }
  • 4

    DRY principle应用于Omar 's solution, here' s 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));
            }
        }
    }
    

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

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

    这还有一个额外的好处,即减少对Razor View开发人员的责任,以确保XSS漏洞的安全性 .


    我对Jacob的解决方案的关注是用CSS渲染换行符打破HTML semantics .

  • 595

    我需要将一些文本分成段落(“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);
        }
    

    用法:

    @Html.ToParagraphs(Model.Comments)
    

相关问题