Recently, I have completed a project and found a small problem. When ReadOnly = "true" is set for TextBox, if a value is added to the control at the front end, it cannot be obtained in the background, the principle of "null" is not clear, and it is unclear why Microsoft is considering it. However, sometimes we want to fill the value through the foreground script and do not want users to modify its control content, this is embarrassing. In the beginning, I switched to <input type = "text" readonly = "readonly"> in Html, but later I found that the workload was heavy, so I searched the internet, the reason why the TextBox ReadOnly = "true" Page fill value cannot be obtained is not found, but the problem is still solved.
In. NET 2.0, when the ReadOnly = "True" attribute is set for a TextBox on the page, assign a value to it through the client script, this value cannot be obtained when you access the Text attribute in the background code. After trying, we found that the problem can be solved in the following ways:
1. Do not set the ReadOnly attribute. Use onfocus = this. blur () to simulate it, as shown below:
<Asp: TextBox ID = "TextBox1" runat = "server" onfocus = this. blur ()> </asp: TextBox>
In this case, the Text box is immediately lost when it gets the focus, so it cannot be manually modified, it can simulate ReadOnly, and the Text attribute can also be used in the background code, normally obtain the value set by the script on the client;
2. After the ReadOnly attribute is set, use the Request parameter as follows:
Front-end code:
<Asp: TextBox ID = "TextBox1" runat = "server" ReadOnly = "True"> </asp: TextBox>
Background code:
String Text = Request. Form ["TextBox1"]. Trim ();
3. Set the read-only attribute of the text box in Page_Load () to read normally, as shown below:
Protected void Page_Load (object sender, EventArgs e)
{
If (! Page. IsPostBack)
{
TextBox1.Attributes. Add ("readonly", "true ");
}
}