Cleaner ClientID's with ASP.NET 4.0

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:

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

This article is part of the GWB Archives. Original Author: Asif Maniar

New on Geeks with Blogs

  • We Won The One Award I Actually Care About

    Full Scale made the Inc. 5000 for the fifth year straight, the 12th listing across my three companies. Here is why the one award you cannot buy is worth stopping for.

  • Your Customers Build the Features Now

    I let a tool I liked sit dead for a year rather than build the features I wanted. An MCP server meant I never had to, and your customers can do the same to your product.

  • Get the Size of a Directory in Linux the Easy Way

    du -sh for the quick answer, ncdu for the cleanup, df for the disk itself: every command for checking directory size in Linux, plus why du and df never agree.

  • Vim Search and Replace: The Ultimate Guide

    One :%s command replaces every match in a file before a find dialog would even open. The Vim substitute patterns worth the muscle memory: flags, ranges, capture groups, and multi-file edits.