Geeks With Blogs
Asif Maniar Software Engineer

A common complain we have had when using ASP.NET web forms is the inability to control the ID attributes being rendered in the HTML markup when using server controls.

Our Interface Engineers want to be able to predict the ID’s of controls thereby having more control over their client side code for selecting/manipulating elements by ID or using CSS to target them.

While playing with the just released VS2010 and .NET 4.0 I discovered some real cool improvements. One of them is the ability to now have full control over the ID being rendered for server controls.

ASP.NET 4.0 controls now have a new ClientIDMode property which gives the developer complete control over the ID’s being rendered making it easy to write JavaScript and CSS against the rendered html.

By default the ClientIDMode is set to Predictable which results in clean and predictable ID’s by concatenating the ID’s of the Parent and child controls. So the following markup:

<asp:Content ID="ParentContainer" ContentPlaceHolderID="MainContentPlaceHolder" runat="server">

    <asp:Label runat="server" ID="MyLabel">My Label</asp:Label>


Will render:


<span id="ParentContainer_MyLabel">My Label</span>

Instead of something like this: (current)

<span id="ct100_ParentContainer_MyLabel">My Label</span>

Other modes include AutoID (renders ID’s like it currently does in .NET 3.5), Static (renders the ID exactly as specified in the code) and Inherit (defers the mode to the parent control).

So now I can write my jQuery selector as:

$(“ParentContainer_MyLabel”).text(“My new Text”);

Instead of:

$(‘<%=this. MyLabel.ClientID%>’).text(“My new Text”);

Scott Mitchell has a great article about this new feature:

Am excited about this and some other improvements. Many thanks to the ASP.NET team for Listening!

Posted on Tuesday, April 27, 2010 10:40 AM ASP.NET , JavaScript | Back to top

Comments on this post: Cleaner ClientID's with ASP.NET 4.0

comments powered by Disqus

Copyright © Asif Maniar | Powered by: