One of the most annoying “features” of the current .Net versions is the automatic generation of the ids for server controls. I’m doing a lot of my work with JavaScript and especially with jQuery, so these unpredictable ids make the selection of elements not only difficult, but also really slow.

Most of the time it’s pretty easy to avoid server controls, but if you want to relay information from the server to the client at startup, you are usually stuck with WebControls like Literals or HTML controls for hidden fields.

At least that was what I thought till I stumbled upon a command to create hidden fields without these horrible long ids in a separate div container right after the form tag:

ClientScript.RegisterHiddenField(string id, string value)

I usually create my fields in Page_Load like this:

using System.Web.UI;
  ...
  protected override void Page_Load(){
      ClientScriptManager csm = Page.ClientScript;
      csm.RegisterHiddenField("foo", "1");
      csm.RegisterHiddenField("bar", string.Empty);
  }

This will create the following HTML code:

<form ...>
  ...
  <div>
      <input type="hidden" id="foo" name="foo" value="1" />
      <input type="hidden" id="bar" name="bar" />
  </div>
  ...
</form>

Of course you won’t be able to read or manipulate the field later like a WebControl. And you have no control about the final placement on the page either. But that was never my intention and you can do whatever you want with the field in your JavaScript anyway.

Comment on this post