ASP.NET 4.0 and ClientID Mode

In this post I will be talking about a new enhancement in ASP.NET 4.0.It is now possible to set the name of your controls ClientID attribute, thanks to the ClientIDMode property. Developers requested a better way of setting names of the web server controls and with the new version of ASP.NET 4.0, this is now a reality.

We can demonstrate this with a new project.I will be using C# and VS 2010.

1) Launch Visual Studio 2010

2) Create a new website, select ASP.NET Web site from the available templates. Save your website by giving it an appropriate name. e.g Clientid

3) Create a master page and add it to the page.Leave the default name.

4) Create a new web user control.Leave the default name.

5) In the WebUserControl.ascx add two web server controls,a label control and a textbox control

6) Add the web user control to the asp.net page by typing in the directives section(top of the page)

<%@ Register src=”WebUserControl.ascx” tagname=”WebUserControl1″
tagprefix=”uc1″ %>

7) Run your application. When the default.aspx page is render by the browser, go to View->Source and you will see something like this:

<div>

<span id=”WebUserControl11_Label1″>what is your name?</span>
<input name=”WebUserControl11$TextBox1″ type=”text” id=”WebUserControl11_TextBox1″ />

</div>

This is how the controls take their name. The first part is the name of the parent control and the second part is the name of the control itself. If you have many nested elements you end up with messy control names.If you wanted to access these controls in external Javascript files, you had no other alternative but to use these names.

8) Switch to the WebUserControl.ascx file in VS 2010, and change the ids of the label and textbox control. For example

<asp:Label ID=”namelabel”
<asp:TextBox ID=”txtlabel”

9) Then we set the ClientIDMode to static for both controls. Save your work and run the application

10) When the default.aspx page is render by the browser, go to View->Source and you will see something like this:

<span id=”namelabel”>what is your name?</span>
<input name=”WebUserControl11$txtlabel” type=”text” id=”txtlabel” />

It is evident that now we have the ID values that we want , and it much easier and handy to use.

The other values for the ClientIDMode are:

  • Legacy: This is equivalent to the ClientID property behavior for earlier versions of ASP.NET. This is also the default value.
  • Predictable:This is used in data controls that use repeating templates. It uses ID attributes of the parent control’s naming containers, but generated IDs do not have names that contain strings like “ctlxxx”.
  • Inherit: This specifies that a control’s ID generation is the same as its parent.


3 Comments

Comments have been disabled for this content.