I love ASP.NET, but one thing I find extremely frustrating is dealing with the automatically generated ID properties that it places on page elements.
For example, let’s say you have a div with an id of “contentTop” like below:
- <div id="contentTop" runat="server" >...</div>
Because you have made the control a server-side control by adding the runat=”server” attribute it will now be rendered with a different ID when it hits the browser (view the source code and you will see). It will get rendered as something like this:
- <div id="ctl00_contentTop" >...</div>
But I don’t want to just complain here, I would like to provide some solutions too.
The solution will be found in the ClientID property of the server-side control. The ClientID property represents the ID that ASP.NET will use for the element on the client.
Using the ScriptManager we place the ClientID in a hidden form field. This can all be done in the code-behind file by using the following code:
- ScriptManager.RegisterHiddenField(this, "contentTop", contentTop.ClientID);
Be sure to have included the ScriptManager to your page, like so:
- <asp:ScriptManager ID="ScriptManager1" runat="server">
- var id = form1.contentTop.value;
- var cTop = document.getElementById('id');
That’s it, if you know of another way, please let us know.