I accidentally saw this description in a foreigner's blog. When the textbox control is set to readonly, and the page's enableviewsate is set to false, the value of the textbox will be lost after submission. This only happens in asp.net 2.0. , this situation will not occur in asp.net 1.0/1.1, the code is as follows:
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" EnableViewState="false" Inherits="_Default" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" " http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd ">
<script runat="server">
protected void Page_Load(object sender, EventArgs e)
{
if (!this.IsPostBack)
{
this.Textbox1.Text = "readonly text";
}
}
protected void Button1_Click(object sender, EventArgs e)
{
this.lblMessage.Text = this .Textbox1.Text;
}
</script>
<html xmlns=" http://www.w3.org/1999/xhtml " >
<head runat="server">
<title>Untitled Page</title>
</head>
<body>
<form runat="server" id="Form1">
<asp:textbox ID="Textbox1" runat="server" ReadOnly="true" ForeColor="silver"></asp:textbox>
<asp:textbox ID= "Textbox2" runat="server" ReadOnly="true">Some Text</asp:textbox>
<asp:Button ID="Button1" runat="server" Text="Button" OnClick="Button1_Click" /><br />
<asp:Label ID="lblMessage" runat="server" Text="Label"></asp:Label>
</form>
</body>
</html>
When running under .net 2.0, the value of the text box will indeed be lost. Finally, I found the MSDN analysis and Microsoft's BUG feedback center. In fact, this is not a BUG, but a small change for security under .net 2.0. The specific excerpt is as follows, so everyone will understand:
Microsoft’s feedback is:
After careful analysis, the explanation for the observed behavior is that:
With a design change in ASP .NET based on user security concern, the input for a readonly textbox is saved in viewstate, which doesn't happen if viewstate is disabled. To workaround this, a page developer can add the readonly attribute to the TextBox.Attributes collection, which can then be used to access the 'value' of the textbox.
We hope this clarifies. Thank you.
Web Server & Tools
MSDN 2005 analysis:
The Text value of a TextBox control with the ReadOnly property set to true is sent to the server when a postback occurs, but the server does no processing for a read-only text box. This prevents a malicious user from changing a Text value that is read-only. The value of the Text property is preserved in the view state between postbacks unless modified by server-side code.
Source: jackyrong blog