Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Show new lines from text area in ASP.NET MVC

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.

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

<%
    string comment = Html.Encode(Model.Comment);
    comment.Replace(VbCrLf, "<br />");
%>
<%= comment %>
like image 535
maff Avatar asked Jun 08 '09 21:06

maff


1 Answers

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();
like image 74
eu-ge-ne Avatar answered Oct 14 '22 15:10

eu-ge-ne