Tuesday, November 2, 2010

ASP.NET Control ClientID and UniqueID, Server control ID

When ever a Server control is rendered in ASP.NET it has two different identifiers, one is named as ClientID which is the "id" attribute and second is the UniqueID which is the "name" attribute.

UniqueID of a control gets the unique, hierarchically qualified identifier for the server control. The fully qualified identifier for the server control, this is the ID which is received as key when value is post back.

The output of button and a text box is like this:
<input type="submit" name="btnLoad" value="Load" id="btnLoad" />
<input type="text" name="txtName" value="Hello" id="txtName" />

Here "name" is what we call btnLoad.UniqueID and "id" is what we call btnLoad.ClientID, in HTML input controls "id" is used for client side validation and other java script things, and "name" attribute is used to identify the field when it is post back to server.

These ID's are in a hierarchy, parent control id first and then child control id, like as follows:
<asp:Repeater ID="rptrNames" runat="server">
<ItemTemplate>
<asp:textbox runat="server" ID="txtName"></asp:textbox>
</ItemTemplate>
</asp:Repeater>

The output of text box is like this:
<input name="rptrNames$ctl00$txtName" type="text" id="rptrNames_ctl00_txtName" />

<input name="rptrNames$ctl01$txtName" type="text" id="rptrNames_ctl01_txtName" />

and so on.

Here ctl00 and ctl01 is Id representing each item of the repeater, txtName is the id for control and rptrNames is the id of repeater control.
The hierarchy of controls is like this:
-Repeater control (Parent control)
--Repeater item (Child control of repeater and parent control of text box)
---TextBox inside each repeater item (Child control of repeater item)

Therefore the UniqueID of textbox is "rptrNames$ctl01$txtName" and ClientID of texbox is "rptrNames_ctl01_txtName".

Another thing noticeable here is the separator between the parent and child control ID's, in case of UniqueID it is "$" dollar sign and in case of ClientID it is "_" underscore. This are fixed control id separators and can be accessed using the read-only property ClientIDSeparator() As Char and read-only property IdSeparator() As Char.

The property ClientIDSeparator() As Char will return (_) underscore and the property IdSeparator() As Char will return ($).

No comments:

Post a Comment