Read-only fields are not stored between roundtrips

We’ve recently upgraded a .NET 1.1 project to 3.5 to benefit from all its goodies. Almost everything went well… with a couple of exceptions.

For a while I’ve been struggling with a stupid bug: read-only fields are not saved during a postback (even with EnableViewState=true).

In this project there are some forms, with fields (asp.net controls) generated dynamically, which means their id’s are not known at design time and on top of that, some are read only (the calendar).

So at first, I did something like this in Page_Load:

string instalationReadyFieldName = "Defaulttemplate1:Content:dtbField1827";
TextBox txtInstalationReady = Page.FindControl( instalationReadyFieldName )
 							as TextBox;
if ( txtInstalationReady != null ) txtInstalationReady.Text =
					Request[instalationReadyFieldName];

But on the test server, surprise, the id’s were different and the fields were not sent to server anymore…

After several hours of searching for an elegant solution, I had an “Ahaa!”: I will use jQuery:

So I removed the readonly attribute from the controls and added some little javascript:

// when pressing a key, don't keep the value.
$(".q_inp_date").live("keypress", function(event)
{
    return false;
});

where ‘q_inp_date’ is the class added to the date, former read-only controls.

Advertisement