views:

1585

answers:

3

I've been writing code for ASP.NET since the start, and today I encountered something I've never seen before. Typically I've looked for line breaks in C# (when posted in ASP.NET from a textarea, for example) by expecting "\r\n". Now I'm using the MVC framework, and the text coming over the wire from a textarea simply has "\n" for line breaks.

Is there something going on in old school TextBox controls that normalizes the line breaks? Since MVC just uses the form data as-is, is this normal? Would love to get some insight.

+3  A: 

\n is the line ending variant on *nix-style systems. \r\n is Windows-specific line-ending behaviour.

If you're checking for line-endings and expose your interface to non-Windows environments, be sure to check not only for \r\n but also for \n alone.

Fore more background, check out the Newline article at Wikipedia.

Kosi2801
@Emil H: Thanks for the correction. Of course you're right, \n is for *nix systems, not \r.
Kosi2801
+2  A: 

I have made observation that the actual line break sequence differs from browser to browser.

If you have a multiline textarea on a page and the page is submitted then:

IE returns "\r\n" to indicate newlines. FF returns "\n" in this case.

I tested it somewhere along the end of 2006, so it may be different now.

I do not believe it could have anything to do with WebForms vs. MVC. Both just process submitted input and return it to you as it is.

If you wish to somehow process and replace these characters it would make sense doing it in the long-to-short order:

string userText = form["Text"];
userText = userText.Replace ("\r\n", "<br/>").Replace ("\r", "<br/>");
User
+1  A: 

I am using Environment.NewLine :

string userText = form["Text"];
userText = userText.Replace (Environment.NewLine, "<br />")

Also take a look at @Haacked's post about some newline textarea quirks.

KP