Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
876 views
in Technique[技术] by (71.8m points)

asp.net - Strange behavior using HTML 'readonly="readonly"' vs. JavaScript 'element.readOnly = true;'

Some background

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)

The issue

When setting the readOnly property of the textboxes with JavaScript, the value in the textbox is submitted with the form: I can see it on the server side (ASP.NET) with myTextBox.Text and it's in Request.Form("myTextBox").

If I set ReadOnly="true" on my <asp:TextBox /> element and don't use the JavaScript method, the value in the text box is NOT available from 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.

My question(s)

What the heck is going on? Is this by design? Is this a browser issue? Did I find a bug? It's annoying that I have to have some extra JavaScript to initially disable the writability of the textboxes when the page loads in order to make my app work.

Thanks!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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:

MyControl.Attributes.Add("readOnly","readOnly")

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...