ASP.NET 4.0 Web Control ClientID
Posted by: Suprotim Agarwal
in Category ASP.NET
Abstract: In ASP.NET 4.0, Microsoft has given developers the control to render client side ID of Server controls, by introducing a new property called ‘ClientIDMode’. In this article, we will explore this property.
In ASP.NET 4.0, Microsoft has given developers the control to render client side ID of server controls, by introducing a new property called ‘ClientIDMode’. It offers the following options to render the server side ‘ID’ at client end –
AutoID – this is the same as previous web server control ‘ID’ rendering at client side.
Static – this option keeps the server ID name intact even at the client side. For example if the Textbox ID at server side is ‘txtCustomerID’ then at client side, it will remain as it is.
Predictable – this option is used for repeating templates like Gridview or Listview.
Inherit – ClientID will be generated the same way as Parent ID. For example, if the ParentID is ‘MainContent’ then the Textbox ‘txtCustomerID’ will be ‘MainContent_txtCustomerID’.
Now let’s see some examples of the same. Create an ASP.NET 4.0 website with the name ‘ClientIDExample’ as shown below –
Now let’s add the following pages to the application –
Make sure that you choose the ‘Site.master’ page when you add the above pages. Now let’s add code for the ‘AutoIDPage.aspx’ –
Note: I have used document.writeln just for illustration purposes. It won’t work in a document that’s served as XHTML.
When you run this page, you will see an output similar to the one shown below –
Now write the following code in our ‘StaticIDPage.aspx’ –
Run this page and you should see the following output –
Now let’s add the following code in ‘InheritIDPage.aspx’ –
In this demo, we are using the Northwind database and Employee table. In the ‘GridView’ control, we are setting two properties – ‘ClientIDMode’ and ‘ClientIDRowSuffix’. The ClientIDRowSuffix property is used during client ID generation. Now run this page. Right click the page in browser and view the source code. You will see the following output –
You can control the web control client ID generation at Page level as well as web site level. For eg: include ClientIDMode property at Page directive as shown below –
If you want to set the ClientIDMode at web site level, you can use the web.config settings as shown below –
In this post, we have seen how easy it is to take control of Client ID generation as per our requirement. The entire source code of this article can be downloaded over here