C# 在 ASP.NET MVC 中显示文本区域中的新行
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/967087/
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
Show new lines from text area in ASP.NET MVC
提问by maff
I'm currently creating an application using ASP.NET MVC. I got some user input inside a textarea and I want to show this text with <br />s instead of newlines. In PHP there's a function called nl2br, that does exactly this. I searched the web for equivalents in ASP.NET/C#, but didn't find a solution that works for me.
我目前正在使用 ASP.NET MVC 创建一个应用程序。我在 textarea 中有一些用户输入,我想用 <br /> 而不是换行符来显示此文本。在 PHP 中有一个名为 nl2br 的函数,它就是这样做的。我在网络上搜索了 ASP.NET/C# 中的等效项,但没有找到适合我的解决方案。
The fist one is this (doesn't do anything for me, comments are just printed without new lines):
第一个是这个(对我没有任何作用,评论只是在没有换行的情况下打印):
<%
string comment = Html.Encode(Model.Comment);
comment.Replace("\r\n", "<br />\r\n");
%>
<%= comment %>
The second one I found was this (Visual Studio tells me VbCrLf is not available in this context - I tried it in Views and Controllers):
我发现的第二个是这个(Visual Studio 告诉我 VbCrLf 在这种情况下不可用 - 我在视图和控制器中尝试过):
<%
string comment = Html.Encode(Model.Comment);
comment.Replace(VbCrLf, "<br />");
%>
<%= comment %>
采纳答案by eu-ge-ne
Try (not tested myself):
尝试(未经本人测试):
comment = comment.Replace(System.Environment.NewLine, "<br />");
UPDATED:
更新:
Just tested the code - it works on my machine
刚刚测试了代码 - 它适用于我的机器
UPDATED:
更新:
Another solution:
另一种解决方案:
System.Text.StringBuilder sb = new System.Text.StringBuilder();
System.IO.StringReader sr = new System.IO.StringReader(originalString);
string tmpS = null;
do {
tmpS = sr.ReadLine();
if (tmpS != null) {
sb.Append(tmpS);
sb.Append("<br />");
}
} while (tmpS != null);
var convertedString = sb.ToString();
回答by nvtthang
Please have a look this answer Replace Line Breaks in a String C#here.
请在此处查看此答案Replace Line Breaks in a String C#。
回答by Moh'd Jamal
to view html tags like a DisplayFor
查看 html 标签,如 DisplayFor
you need to use another method , in fact the mvc dosent allowed you to view tags in page
您需要使用另一种方法,实际上 mvc 允许您查看页面中的标签
but you can used this to ignore this option
但是你可以用它来忽略这个选项
@Html.Raw(model => model.text)
good luck
祝你好运
回答by Donskikh Andrei
@Html.Raw(@Model.Comment.RestoreFormatting())
@Html.Raw(@Model.Comment.RestoreFormatting())
and than...
然后...
public static class StringHelper
{
public static string RestoreFormatting(this string str)
{
return str.Replace("\n", "<br />").Replace("\r\n", "<br />");
}
}