显示换行符asp.net的MVC剃刀 [英] display line breaks asp.net mvc razor

查看:922
本文介绍了显示换行符asp.net的MVC剃刀的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我用下面让文本输出中输入的换行符< textarea的方式> HTML元素

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?

推荐答案

您code很容易受到XSS攻击,因为它不带HTML code中的文本。我建议你​​以下内容:

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

这篇关于显示换行符asp.net的MVC剃刀的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆