ID,ClientID和UniqueID - .net语言 -

ID,ClientID和UniqueID

时间:2010-01-27 00:02:11   来源:   评论:加载中...   点击:加载中...
在ASP.NET 的服务器端控件中有三种关于 ID 的属性,即 ID, ClientID 和 UniqueID。ID 表示控件的服务器端编程的标识符,我们写"服...
Page.FindControl(Request.Form["__EVENTTARGET") As IPostBackEventHandler;

if (postBackInitiator != null)
postBackInitiator.RaisePostBackEvent(Request.Form["__EVENTARGUMENT"]);

You can use the UniqueID property to find any control no matter how deep it is nested in the control hierarchy. Just pass its value to the FindControl method of the Page.

ClientID
The ClientID property is quite similar to the UniqueID. It is generated following the same rules (the ID of the control prefixed by the ID of its NamingContainer). The only difference is the separator - for the ClientID it is the "_" (underscore) symbol.
The ClientID property is globally unique among all controls defined in an ASP.NET page. You may ask why we need two different globally unique properties. The answer is that ClientID serves a different purpose than UniqueID. In most server controls the ClientID property provides the value for the HTML "id" attribute of the HTML tag of that server control. For example this:

<asp:Label ID="Label1" Text="Label" />

will render as this:

<span id="Label1">Label</span>

That's why you often use the following JavaScript statement to access the DOM element corresponding to some ASP.NET server control:

var label = document.getElementById("<%= Label1.ClientID%>");

which in turn renders as:

var label = document.getElementById("Label1");

It is worth mentioning that the values of the ID, UniqueID and ClientID will be the same if the control is defined in the master page (or the page). This however can often lead to unexpected errors. If the ID of the control is hardcoded inside the JavaScript statement (e.g. "Label1") this code will only work provided the control is defined in the Page or master page. Moving the control and the JavaScript code into a userc control with ID "UserControl1" will fail at runtime because the control will now render as:
<span id="UserControl1_Label1">Label</span>


That's why you should prefer using the "<%= Label1.ClientID%>" syntax to get the client-side id of server controls.


Additionaly the ClientID is used in ASP.NET Ajax as the unique identifier of client-side controls. Thus the following JavaScript statement is commonly used:

var control = $find("<%= MyControl1.ClientID %>");



相关热词搜索:

 
上一篇:DataGrid的自动编号问题
下一篇:C#中COOKIES的实现存取
收藏 将此文推荐给朋友
分享到:
推荐资讯