Daniel Ballinger
Daniel Ballinger

Reputation: 13537

Carriage Return (ASCII chr 13) is missing from textbox postback values when used within an ASP.NET Update panel

I have an ASP.NET TextBox with TextMode = TextBoxMode.MultiLine that is used within an AJAX Update Panel. The .Text value has been pre-set to a value that has multiple lines.

When using Chrome(7.0.517.41) or Firefox(3.6.11) working with the controls posted back value on the server the carriage return is lost if the user hasn't edited the pre-set value.

E.g. Initial .Text value set when the page loads:

"line 1/r/nline2/r/nline3"

Value of .Text on postback from Chrome or Firefox where the user has editied the textbox:

"line 1/r/nline2/r/nline3"

Value of .Text on postback from Chrome or Firefox where the user has not editied the textbox:

"line 1/nline2/nline3"

Why is the carriage return being lost and how can I resolve this?

Upvotes: 3

Views: 4674

Answers (2)

Zeek2
Zeek2

Reputation: 424

The earlier answer didn't quite work for our application - the replacement characters displayed visibly and added to the character count (length) of the multi-line asp:textbox - but the following variant does work for us (in VB):

txbTextMessage.Text = Regex.Replace(txbTextMessage.Text, "\n\n", vbCrLf & vbCrLf)
txbTextMessage.Text = Regex.Replace(txbTextMessage.Text, "([^\r])[\n]", "$1" & Environment.NewLine)

The topline deals with the \n\n\n\n issue described by other respondents.

BTW Those using C# may find Environment.NewLine a useful alternative to vbCrLf; they are not exactly the same in all environments but are used interchangeably in the above code.

Perhaps it might help someone.

Upvotes: 0

Daniel Ballinger
Daniel Ballinger

Reputation: 13537

I've found a blog post by Craig Wardman Textbox CrLf in Firefox using AJAX UpdatePanel that discribes the same problem.

When using a MultiLine textbox inside an ASP.NET AJAX update panel, you may encounter problems with carriage return line feeds in your text on the server using Firefox (and potentially other browsers).

Internet Explorer uses the Windows style CrLf (13 10) for newlines in a textarea but Firefox uses Unix style Lf (10) only.

On a synchronous postback it seems ASP.NET fixes this and you will get CrLf in your text on the server. However, when you are posting back asynchronously using AJAX, you only get Lf in your text when Firefox is used.

His proposed solution is to resolve the issue server side:

public static string CleanUnixCrLf(string textIn)
{
   //firefox only uses Lf and not CrLf
   return System.Text.RegularExpressions.Regex.Replace(textIn, "([^\r])[\n]", "$1\r\n");
}

This will work, but I'd be interested in a solution that could fix the issue without having to check every posted back value.

Edit

This solution doesn't handle multiple adjacent new lines. Appending .Replace("\n\n", "\n\r\n") to the other replace is one option.

Upvotes: 6

Related Questions