The TextBox Control in ASP. NET uses the ReadOnly = "true" attribute.

Source: Internet
Author: User

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 ");
}
}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.