Shane Bauer Blog
.NET, ASP.NET and Software Development

ASP.NET: Web Controls have an ID, a ClientID and a UniqueID. What's the deal?

November 8, 2006 11:05 by sbauer

While working on your ASP.NET page, you may have noticed that all of your web controls contain three different ID properties. That's great. But why? Uniqueness.

Lets say, for example, you have a Repeater control. In this Repeater control, you have an itemtemplate that contains a textbox and a label. Your label is called "ProductName" and your textbox is called "ProductQuantity". If your repeater contained more than one item, you would run into issues with html elements being named the same. That's a huge problem.

UniqueID fixes this issue. When the control gets created, a uniqueId is generated based on the control's heirarchy. For example, a textbox within a CreateUserWizard would have a UniqueID similar to "CreateUserWizard1$CreateUserStepContainer$Email". The UniqueID, as you can see, is a large string seperating the control's parents by a dollar sign. Pretty simple.

However, that's not technically valid in the HTML world. ClientID fixes this problem. ClientID replaces the invalid separator with a valid separator, like an underscore. Therefore, the textbox within the CreateUserWizard would have a ClientID similar to "CreateUserWizard1_CreateUserStepContainer_Email". As a result, when your textbox is rendered as a standard input element, the ID field would contain the value in the ClientID property.

If you want to access your control via javascript, don't use the ID property, and don't use the UniqueID property. Use the ClientID Property.

ConfirmButton.Attributes.Add("OnClick","javascript: alert('The username textbox as a value of " + Username.ClientID + "')";


Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5
Tags:
Categories: .NET
Actions: E-mail | Permalink | Comments (0) | Comment RSSRSS comment feed

Related posts

Comments are closed