Suppose you a have a text box in an ASP.Net page. This text box needs to contains calculated values from other inputs that will be received from the user (other text boxes). The user can not change the text in the
How do you implement that? By using the
ReadOnly property in the
In the following weekend I thought about it all the time and then it came to me: The
MSDN explains it: The Text value of a
TextBox control with the
ReadOnly property set to
true is sent to the server when a post-back 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 post-backs unless modified by server-side code.
It doesn't get any simple then that. In general the value of a
ReadOnly text box can only be changed by server code.
How to solve the bug?
There are two ways:
- Recalculate the value of the
TextBoxin the server after a post-back and set it there. The problem in this is duplicated code. The same calculation is performed in a script and in the server code, so any future modification in the calculations need to be done in both.
- Use the readOnly attribute of the input tag. This prevents the user from manually change the value of the
TextBoxand the value is still sent to the server. To do this you need to run the following code:
Here's a code example for the problem and the second solution:
You can see:
- TextBox which contains the value.
- Input button which changes the value of the text box incrementing it's value by one.
- ASP.Net button which simply perform a post-back.
Try to run it with and without the commented line which sets the
ReadOnly to true, and see how the value of the textbox is being reset after a post-back.
The lesson that I've learned after solving this bug: Sometimes the most strange and complex problems have a simple solution.
P.S.: I think using a relying on a calculating value from the client is a bad practice. The page that is presented to the user is the UI. It is not suppose to perform calculations. This is the server code job. So if I had to rewrite the page I would choose the first solution.