Search code examples
htmltextareavisual-web-developer

Keep linebreaks when getting text from <textarea>


I'm building a site with Visual Web Developer with C# and HTML.

I have a page where users can write feedback about my site in a textarea tag and then submit (in the textarea they can do a line-break everywhere).

The problem is that when I get back the text they wrote it appears without the linebreaks, for example:

if the user wrote:

"Hello, my name is
Omer N."    

When I get it back it will look like this: "Hello, my name is Omer N.".

How can I fix this problem?


Solution

  • Depends on how you are storing the values. Remember that HTML and general input from fields following the whitespace rule, it will truncate/condense white space into a single entity.

    So "Wide      String" = "Wide String" and:
    
    "Multi-line
    string
    here" will be truncated to "Multi-line string here" as you have experienced.
    

    This is the default behavior.

    So to keep your line breaks, spacing, etc.. you need to escape it or a process of encoding and decoding, before storing it.

    It is explained here:

    Many newcomers to web development cannot get their head around why the carriage returns they made in their data on input from a textarea, or from a text file, Excel spreadsheet etc. do not appear when the web page renders.

    The solution is fairly obvious once the newcomer realizes that a web page is only the browser's interpretation of html markup, and that a new line in html is represented by the
    tag. So what is needed is a way to swap carriage returns or line feeds with the
    tag. Well, a way to Replace() them, actually.

    <%# Eval("MyMultiLineValue").ToString().Replace(<linebreak>,"<br />") %>
    

    The string.Replace() method allows this, but we also need to identify what we want to replace with the html tag. How is a new line represented in C# or VB.Net?

    In C#, it's "\r\n", while in VB.Net, it's vbcrlf. However, there is also a language independent option that does just the same thing: Environment.NewLine.

    <%# Eval("MyMultiLineValue").ToString().Replace(Environment.NewLine,"<br />") %>
    

    Hope this helps! :)