How to stop ASP.NET from changing IDs in order to use jQuery How to stop ASP.NET from changing IDs in order to use jQuery asp.net asp.net

How to stop ASP.NET from changing IDs in order to use jQuery


Short answer:

Set ClientIDMode="Static"

<asp:Label ID="myLabel" ClientIDMode="Static" runat="server" Text="testing"></asp:Label>

Long answer:

.NET 4 now has the ability to let you choose your ClientIDMode:

Type: System.Web.UI.ClientIDMode
A value that indicates how the ClientID property is generated.

AutoID
The ClientID value is generated by concatenating the ID valuesof each parent naming container with the ID value of the control. Indata-binding scenarios where multiple instances of a control arerendered, an incrementing value is inserted in front of the control'sID value. Each segment is separated by an underscore character (_).This algorithm was used in versions of ASP.NET earlier than ASP.NET 4.

Static
The ClientID value is set to the value of the ID property. Ifthe control is a naming container, the control is used as the top ofthe hierarchy of naming containers for any controls that it contains.

Predictable
This algorithm is used for controls that are in data-boundcontrols. The ClientID value is generated by concatenating theClientID value of the parent naming container with the ID value of thecontrol. If the control is a data-bound control that generatesmultiple rows, the value of the data field specified in theClientIDRowSuffix property is added at the end. For the GridViewcontrol, multiple data fields can be specified. If theClientIDRowSuffix property is blank, a sequential number is added atthe end instead of a data-field value. This number begins at zero andis incremented by 1 for each row. Each segment is separated by anunderscore character (_).

Inherit
The control inherits the ClientIDMode setting of its NamingContainer control. This is the default.


instead of using this selector

$('#Label1')

use this one, basically you are using the classic asp inline server side code.

$('#<%= Label1.ClientID %>')

this will insert whatever ID that is generated to be placed as a literal.

If you wish to use external files then I would suggest you create an obj that is global on the page to hold all of your client ids and then reference that obj within your external files (not ideal but it is a solution)

var MyClientIDs = {    Label1 = '<%= Label1.ClientID %>',    Label2 = '<%= Label2.ClientID %>',    Textbox1 = '<%= Textbox1.ClientID %>',    Textbox2 = '<%= Textbox2.ClientID %>'};

and then in your external file you can access Label1 for example: $('#' + MyClientIDs.Label1)


In .NET 4+ set ClientIDMode="Static". This will solve your problem.

Example:

<asp:Label ID="Label1" ClientIDMode="Static" runat="server" Text="test"></asp:Label>