Show new lines from text area in ASP.NET MVC

19,911

Solution 1

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

Solution 2

to view html tags like a DisplayFor

you need to use another method , in fact the mvc dosent allowed you to view tags in page

but you can used this to ignore this option

@Html.Raw(model => model.text)

good luck

Share:
19,911
maff
Author by

maff

Updated on June 13, 2022

Comments

  • maff
    maff almost 2 years

    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 %>
    
  • CoderDennis
    CoderDennis almost 15 years
    System.Environment.NewLine refers to the server's environment, no? Would this work if the client's browser was a different environment?
  • Patricia
    Patricia over 14 years
    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!