Sunday, March 6, 2005

Setting hidden fields in a User Control

[This was originally posted at]

Hidden fields are so powerful in UserControls because they are a bridge between the client and server. JavaScript can set a hidden field value, and then the server can get that value (given that the field is runat=server). Therefore it is very common for UserControls to need to set the values of hidden fields from the client.

While it's easy to hard-code a simple case, truly reusable controls (such as calendars or employee look-ups) are more tricky. It can especially be frustrating when you've created a control, and then a co-worker tells you it's "broken" because they're using it in a legitimate way that you didn't anticipate. There are several cases that any such control should pass:

  1. Can you change the name of an instance of the control.
  2. Can it be nested in another UserControl?
  3. Can multiple instances of the UserControl be on the page at once?
  4. Can it handle the page's form name being changed (it might not always be Form1)?

There are two other issues to at least be aware of:

  1. Does it have external dependencies, like relying on Session State or QueryString values?
  2. Can it run in both IE and NN?

Ultimately the HTML to reference the hidden field from within the same page (i.e. not a popup) is something like:


We can see that here the Form and UserControl name are both hard-coded. The hidden field is prefixed with the UserControl Id. We can handle the form by referencing it as forms[0] instead of merely the default name like "Form1". Note that an Aspx page should only have 1 form (runat=server) per page, so this is a fair assumption.

We can handle the nested UserControl by making the name as a string and choosing either function below to translate this into actual JavaScript code:

  • use getElementById(string) - given the Id as a string, get the control.
  • use eval(string) - given the script as a string, evaluate it.

For example, we could pass in the variable strUcName (which contains the UC name) into a JavaScript function to reference the following hidden field:

document.getElementById(strUcName + '_HdnOrgId').value =myValue;

The UserControl name, strUcName, can be obtained from the UserControl itself at the server with ClientID.

By dynamically assembling the JavaScript to reference the hidden field, referencing the form as forms[0] instead of a hard-coded name, and passing in the UserControl's ClientID, we fulfill the first four criteria listed above. I will cover the other two criteria in another post.

No comments:

Post a Comment