我在 MultiLine 模式下有 TextBox。 Text 属性包含一些换行符 (\r\n)。
为什么返回到服务器的数据在完整回发 和异步回发 上返回“\r\n”之间存在差异 - 返回“\n” ?
用户代理: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]");
}
输出:
- 异步回发:Line1[LF]Line2[LF]Line3
- 完整回发:Line1[CR][LF]Line2[CR][LF]Line3
最佳答案
如果您使用 Firefox/Chrome 或其他使用类 Unix LF
(ASCII 中的 0x0A
)作为行尾的浏览器,该行为是设计使然,如前所述在 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.
但是在使用 Windows 风格的行结尾(CRLF
/0x0D0A
in ASCII)的 IE 中,相同的异步回发返回所需的结果,如下图所示:
呈现不同行为背后的原因是在标准回发中,由多行 TextBox
控件生成的 textarea
使用完整的 POST
将其内容发送到服务器方法,并遵循以服务器端进程结尾的 Windows 样式行。然而,在异步回发中,只有 UpdatePanel
的内容会通过依赖于浏览器的 AJAX 请求进行更新。
Craig Wardman 在使用类 Unix 行尾的浏览器中证实了这种行为,并提出了一个解决方案,以使用 Regex.Replace< 来标准化服务器端同步和异步回发的
(参见引用部分)。CRLF
的使用
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.
引用资料:
关于asp.net - 与多行 asp :TextBox on full postback vs. 异步回发不同的换行符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48504740/