Referencing Server Controls in Javascript .NET 2.0

By ecliptic

Ahhh.. the joys of getting client script and server script to communicate. I came across an issue with trying to javascript to validate some server controls (asp:textboxes, asp:checkboxes, etc) before submitting the form. Well, I assigned the ID and then in my javascript I said document.getElementById(‘ID’) and kept on getting a object reference not found error. After trying a few things out, I realized two key points:

  • Defensive programming is a must in javascript.
  • Server controls are assigned a unique ID as they are rendered by ASP.NET.

There is a ClientID and an ID for server controls. The ClientID (if you look at the client html) is what gets assigned an ID. So what you have to do is either pass the ClientID into javascript…. or use the handy dandy ClientScript.RegisterClientScriptBlock in the asp code to register the client script and pass the Control.ClientID into it. Pretty cool stuff. Enjoy!

Leave a Reply