转载:http://hi.baidu.com/tlq_1983/blog/item/ab8f4bfc30188ff5fd037f18.html
The difference between ID, ClientID and UniqueIDI this post I will try to explain thedifference between those three commonly used properties. Eachproperty is described in a separate section. Attached you can finda sample web site as well as two screenshots visually depicting thedifference between the ID, ClientID and UniqueIDproperties. ID UniqueID For example if a Label with ID="Label1"is defined in a user control with ID = "UserControl1" the UniqueIDof the Label will be "UserControl1$Label1". Adding another instanceof the same user control (with ID = "UserControl2") will make theUniqueID of its child label to be "UserControl2$Label1". The UniqueID propertyis also used to provide value for the HTML "name" attribute ofinput fields (checkboxes, dropdown lists, and hidden fields).UniqueID also plays major role in postbacks. The UniqueID propertyof a server control, which supports postbacks, provides data forthe __EVENTTARGET hidden field. The ASP.NET Runtime then uses the__EVENTTARGET field to find the control which triggered thepostback and then calls its RaisePostBackEvent method. Here is somecode which illustrates the idea: IPostBackEventHandlerpostBackInitiator = Page.FindControl(Request.Form["__EVENTTARGET") AsIPostBackEventHandler; if (postBackInitiator!= null) You can use theUniqueID property to find any control no matter how deep it isnested in the control hierarchy. Just pass its value to theFindControl method of the Page. ClientID <asp:Label ID="Label1"Text="Label" /> will render as this: <spanid="Label1">Label</span> That's why you often use the followingJavaScript statement to access the DOM element corresponding tosome ASP.NET server control: var label =document.getElementByIdx("<%=Label1.ClientID%>"); which in turn renders as: var label =document.getElementByIdx("Label1"); It is worth mentioning that the valuesof the ID, UniqueID and ClientID will be the same if the control isdefined in the master page (or the page). This however can oftenlead to unexpected errors. If the ID of the control is hardcodedinside the JavaScript statement (e.g. "Label1") this code will onlywork provided the control is defined in the Page or master page.Moving the control and the JavaScript code into a userc controlwith ID "UserControl1" will fail at runtime because the controlwill now render as:
var control = $find("<%=MyControl1.ClientID %>"); |