Monday, September 7, 2009

What is clientID in asp.net and how it is used

what is clientID?

Ans:
In javascript we write:
var lblTitle = document.getElementById("<%=lbltitle.ClientID%>");
gives Control of label in javascript.

The ClientID property gets a reference to the ID assigned to the control at runtime.

If you give a name to a label then at time of rendering that aspx page to html final page, Name mangling take place.

This name mangling is done because

1.If a control(label,textbox etc) placed in one container (Datalist,repeater etc)
can have same name as of controls in other parent controls or there child controls
At time of rendering whole Page is renderd as one HTML page, thus name mangling is done so that each label will have unique id.

Example
There is a imagetag (id="Image1") in Datalist which is in tab container :
Id will become: "ctl00_main_TabContainer1_tab_Detail_Image1"

In these instances, when a control is nested inside a control that implements INamingContainer, the controls ID will be appended at runtime to ensure that it is unique.

* It is situations like that where you'll need to refernce it by ClientID.


In javascript if u write like this:
var imgElement= document.getElementById('Image1');
then this wont be working because of name mangling.

so solution is :

1. document.getElementById('<%=Image1.ClientID%>').style.display = '';
2. Run the HTML Page Fing the Image tag by veiw source in IE or Firefox.
Get it's Client id (Id of that image tag in view source of that page on Browser)
write:
var imgElement = document.getElementById('ctl00_main_TabContainer1_tab_Detail_Image1');

This is Significance of Client id.