Make Input and Select as Readonly

I have using controls for a long time and hence seldom need to use the html controls directly on a webpage. However today working on a project where I was emitting the web page (html) in the Page Render method I was emitting the core html controls. There was a need to make the control readonly or disabled as many of us call it more often, including myself. So I used the attribute disabled and added to the input control. Like this

<input type=”text” value=”whatever” name=”control1″ disabled/>

Now this will surely make the control disabled and readonly. However the funny thing is a disabled control doesn’t pass the value in it back to the server on submit. So if you analyse Request.Params[“control1”] on postback or submit it will be empty. In order to get the value on postbacks and make the control readonly at the same time use the attribute Readonly instead. This will ensure the textbox retains its values on the submit.

So the correct way to do is

<input type=”text” value=”whatever” name=”control1″ readonly/>

However things are not simple when using the Select control. <SELECT …> does not have a Readonly attribute. The reason is that technically <SELECT …> lists don’t have values… they have selected options, which themselves have values.  So one way is to do the way Claus has suggested here. However the correct way is to display the value in an input tag using the attribute Readonly.

Happy Coding.