3

I have TextBox in MultiLine mode. Text property contains some newlines (\r\n).

Why there is a difference between data returned to server on full postback — "\r\n" is returned and on async postback — "\n" is returned?

User agent: IE, Firefox, Edge, Chrome


aspx:

    <asp:UpdatePanel runat="server" ID="up">
        <ContentTemplate>

            <asp:TextBox runat="server" ID="tbText" TextMode="MultiLine" Height="200px" />

            <asp:Label runat="server" ID="lDump" /><br />
            <asp:Button runat="server" ID="btnAsync" Text="Async postback" />

        </ContentTemplate>
    </asp:UpdatePanel>

    <asp:Button runat="server" ID="btnFull" Text="Full postback" />

aspx.cs:

    protected void Page_Load(object sender, EventArgs e)
    {
        btnAsync.Click += Dump;
        btnFull.Click += Dump;

        if (!IsPostBack)
            tbText.Text = "Line1\r\nLine2\r\nLine3";
    }

    private void Dump(object sender, EventArgs e)
    {
        lDump.Text = tbText.Text.Replace("\r", "[CR]").Replace("\n", "[LF]");
    }

output:

  • Async postback: Line1[LF]Line2[LF]Line3
  • Full postback: Line1[CR][LF]Line2[CR][LF]Line3
tibx
  • 840
  • 13
  • 20

1 Answers1

1

The behavior is by design if you're using Firefox/Chrome or other browsers which use Unix-like LF (0x0A in ASCII) as line ending, as noted in this post:

The most common difference (and probably the only one worth worrying about) is lines end with CRLF on Windows, NL (LF) on Unix-likes, and CR on older Macs (the situation has changed with OS X to be like Unix). Note the shift in meaning from LF to NL, for the exact same character, gives the differences between Windows and Unix.

However in IE which uses Windows-style line ending (CRLF/ 0x0D0A in ASCII), the same async postback returns desired result, as shown in image below:

CRLF in IE vs other browsers

The reason behind different behavior presented is in standard postback, textarea produced by multiline TextBox control sends its content to the server using complete POST method, and follows Windows-style line ending in server-side process. However in asynchronous postback, only contents of UpdatePanel updated with browser-dependent AJAX requests.

Craig Wardman confirmed this behavior in browsers using Unix-like line endings, and proposed a solution to standardize usage of CRLF for both synchronous and asynchronous postback in server side with Regex.Replace (see references section).

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.

References:

Asynchronous and synchronous postback in ASP.NET

Textbox CrLf in Firefox using AJAX UpdatePanel

Tetsuya Yamamoto
  • 24,297
  • 8
  • 39
  • 61