So I was finishing up some enhancements in a web application that does some automatic interpolation of data. There are a handful of textboxes that the user fills out, and other textboxes in between them have values automatically calculated. The textboxes that receive automatically calculated values must be readOnly to prevent user changes, but can’t be disabled or they won’t get submitted on postback. Each of these textboxes also has a checkbox next to it so a user can consciously check it to make the field writable and thus allow them to override the interpolated value.
The browser: IE 7 (not sure how this behaves in others)
When setting the
myTextBox.Text and it’s in
If I set
ReadOnly="true" on my
myTextBox.Text (I assume it never made it into the
ViewState), but it is getting submitted with the form:
Request.Form("myTextBox") has a value.
Here is Solutions:
We have many solutions to this problem, But we recommend you to use the first solution because it is tested & true solution that will 100% work for you.
This is by design. As an ASP.NET security feature, setting it to readonly on the server will keep it readonly regardless of what happens on the client. If you want them to be able override it and actually submit a value then it’s not really readonly on the server, only conditionally on the client. You can either do a postback when they check the checkbox to change the readonly attribute on the server, or set only the readonly attribute on the client using this ASP.NET code:
Alright, I tweaked my sample and I think I see the problem – and I could be wrong, but I think it’s behaving as intended.
When you set a field to be ReadOnly on the codebehind, the
ASP:TextBox seems to become immutable even by JS. I made a change and the change was reflected in JS and in the form, but the TextBox retained its original text value — unless I looked in the Request. Form as you did.
I don’t think this is a bug. I think it’s intentional, to keep something completely locked down – readonly on the server side hanging on does seem like a preferred choice.
May I suggest something using hidden input fields and spans or
ASP:Labels (which effectively render as spans) to give a display aspect that isn’t adjustable by the user?
Alternately, if you have access to a JS library (such as jQuery), you could set a CSS class on your TextBoxes (with
CssClass="readonly" or something like that in your tag), then use the selection process to tweak the attribute, like so (assuming jQuery, easily written in other languages):
That way, you’re not rewriting much of your markup and it’s a quick’n’easy JS fix.
Note: Use and implement solution 1 because this method fully tested our system.
Thank you 🙂