To prepare the test project follow these steps:
- Create new web application project.
- Create new master page (Site1.Master).
- Create new content page (ContentPage.aspx) that uses previously create master page.
- Create new web user control (UserControl1.ascx).
- Add checkbox to user control and assign values to its ID and Text properties.
My pages are here. If you don’t want to copy-paste these then scroll down, right to the end of this mark-up block.
Now we have pages and user control created and it is time to run our application. When application opens in browser let’s see the source of page. Our special interest is the checkbox and how it is rendered. We should see something like this:
As we can see we have id that is hardly bound to the location of control in control tree. This is not something we want when we want client-side scripts to do something with server-side controls.
Changing ClientID of control using ClientIDMode
ASP.NET 4.0 has new attribute for controls: ClientIDMode. Using ClientIDMode attribute it is possible control how controls get their client-side ID-s. Let’s try out the following definition for checkbox.
As you can see I set ClientIDMode to value Static. Let’s see the ID of checkbox now.
As we can see checkbox has now both ID in server and client side, just as we wanted. The name of control is still like before but somehow ASP.NET has to know where control is located in page’s control hierarchy.
To find out more about ClientIDMode you can read ClientIDMode documentation from MSDN Library.