Cleaner ClientID's with ASP.NET 4.0

Posted by amaniar on Geeks with Blogs See other posts from Geeks with Blogs or by amaniar
Published on Tue, 27 Apr 2010 08:40:07 GMT Indexed on 2010/04/27 14:54 UTC
Read the original article Hit count: 253

Filed under:

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>

</asp:Content>                                                                                                                                                            

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:

http://bit.ly/ailEJ2

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

© Geeks with Blogs or respective owner