maf*_*aff 9 c# string asp.net-mvc text
我目前正在使用ASP.NET MVC创建一个应用程序.我在textarea中有一些用户输入,我想用<br />而不是换行显示这个文本.在PHP中有一个名为nl2br的函数,它就是这样做的.我在网上搜索了ASP.NET/C#中的等价物,但没有找到适合我的解决方案.
第一个就是这个(对我没有任何意义,评论只是印在没有新线的情况下):
<%
string comment = Html.Encode(Model.Comment);
comment.Replace("\r\n", "<br />\r\n");
%>
<%= comment %>
Run Code Online (Sandbox Code Playgroud)
我找到的第二个是这个(Visual Studio告诉我VbCrLf在这个上下文中不可用 - 我在视图和控制器中尝试过):
<%
string comment = Html.Encode(Model.Comment);
comment.Replace(VbCrLf, "<br />");
%>
<%= comment %>
Run Code Online (Sandbox Code Playgroud)
eu-*_*-ne 26
尝试(不自己测试):
comment = comment.Replace(System.Environment.NewLine, "<br />");
Run Code Online (Sandbox Code Playgroud)
更新:
刚刚测试了代码 - 它可以在我的机器上运行
更新:
另一种方案:
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();
Run Code Online (Sandbox Code Playgroud)