Getting the ID of .NET Controls for use with jQuery on ASP.NET webforms

When you drop a .NET control on a page and give it an ID, you may expect that the ID will be the same on the published page of your application and that the ID will work in jQuery – but you may be disappointed!

Say we place a dropdown list of rooms on our .NET page:

<asp:DropDownList ID=”cboRooms” runat=”server” AutoPostBack=”False” EnableViewState=”False”>
</asp:DropDownList>

If we want to access this in jQuery, you may think we can use $(‘#cboRooms’) as a selector. Alas,  no! The control rendered to the page will be a standard HTML but the ID is decorated according to where it sits in the page.

For example, if this control is on a page that has a Master Page, it gets rendered something like:

<select id=”ctl00_BodyContent_cboRooms” name=”ctl00$BodyContent$cboRooms”>

If this is in a User Control it may look like this:

<select id=”ctl00_BodyContent_UserControl1_cboRooms” name=”ctl00$BodyContent$UserControl1$cboRooms”>

We can work out this convention easy enough, or use something like Firebug to show us how the control has been named, but it’s going to be a pain – and somewhat dangerous – if this ID is going to change when we visually drag-and-drop the control in Visual Studio.

Luckily we have a simple way out. We can force .NET to give us the ID when it renders it by using an inline expression called a  displaying expression.  If we want the value of this control,  instead of

$(‘#cboRooms’).val()

use:

$(‘#<%=cboRooms.ClientID%>’).val()

The ClientID will be the ID of the control as rendered to the HTML page.

Les Kendall (@LesKendall)

For more about Inline Expressions, see
Introduction to ASP.NET inline expressions in the .NET Framework