IDing the Problem of ASP.NET
Wednesday, August 20th, 2008I 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>
This is because ASP.NET generates its own IDs to ensure that every element on the page has a unique ID. Developers that work with JavaScript and CSS will immediately see the problem. This causes difficulty when using JavaScript and CSS which rely on those IDs to reference elements, as they can’t easily predict what the generated ID will be. When it comes to CSS specificity the ID selector is extremely useful. In addition, anyone that uses JavaScript knows that getElementById (or one of the JavaScript library ways) is the most popular way to target an element. So why the hell does ASP.NET do this to us? Honestly, I can’t really tell why, other than the fact that they must not trust us enough to be able to uniquely ID our elements ourselves.
But I don’t want to just complain here, I would like to provide some solutions too.
Solution
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">
- </asp:ScriptManager>
Now we can use JavaScript to retrieve the value from our hidden form fields.
- var id = form1.contentTop.value;
- var cTop = document.getElementById('id');
That’s it, if you know of another way, please let us know.
Happy coding.