views:

960

answers:

1

Hi,

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 %>

Maybe someone can tell me how to achieve this, should be a standard problem ;)

Thanks in advance, Mathias

+7  A: 

Try (not tested myself):

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();
eu-ge-ne
Perfect, thanks :)
Mathias
It works on your machine? http://www.codinghorror.com/blog/archives/000818.html
Tomas Lycken
System.Environment.NewLine refers to the server's environment, no? Would this work if the client's browser was a different environment?
Dennis Palmer
I had this same problem. The first solution fixed it for one of my text areas. but I needed to use a char(10) for one of the others. the only difference was one was submitted ajaxly and the other normally. just thought i'd add this incase someone else had the same problem!
Patricia
Second solution works better. Thanks
Nick Masao