Saturday, August 19, 2006

.NET and Read-only Text Fields

A note of caution to all .NET developers: if you change a read-only text field (with runat="server") with javascript on the browser, you will not see the change in the Text property after a postback. However the value is sent by the browser and it is present in the Request parameters. This does not apply if you change the value from the server side.
This caused me and my colleagues a lot of headaches.
To work around it you can use a the Request directly, ahidden field to double the value or, if you use inheritance, override the method LoadPostbackData with the following code:

protected override bool LoadPostData(
string postDataKey, NameValueCollection postCollection)
string text1 = this.Text;
string text2 = postCollection[postDataKey];
if (!text1.Equals(text2, StringComparison.Ordinal))
this.Text = text2;
return true;
return false;

If you are curious, use Lutz Roeder's .Net Reflector and take a look of the original implementation.

No comments: