Welcome 微信登录

首页 / 网页编程 / ASP.NET / ASP.NET 4.0中的控件ID

ASP.NET 4.0中的控件ID2010-11-05 博客园 kaixingirl在.NET 4.0中,当将控件添加到页面或者用户控件,有一个新的选择项:ClientIDMode。此属性为您提供四种选择:Legacy, Static, Predictable, Inherit。在此之前,几乎不可能找到在一个正确的控件的ID。现在在ASP.NET4.0中,选择Legacy将与以前的版本产生的方式相同,连接每个控件的ID和父容器的名字。设置为Static将生成服务器控件ID属性设置的值。Predictable用于控件的数据绑定,如 repeater控件,而且还要使用ClientIDRowSuffix属性。

在下面的例子,两个列表在一个页面的ContentPlaceHolder内创建,使用相同的数据源。第一个使用默认的,第二个使用 Static 。

1 <asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" runat="server">
2 <asp:XmlDataSource ID="LinkData" runat="server" XPath="Colors/Color">
3 <Data>
4 <Colors>
5 <Color Name="Red"/>
6 <Color Name="Blue"/>
7 <Color Name="Yellow"/>
8 <Color Name="Green" />
9 </Colors>
10 </Data>
11 </asp:XmlDataSource>
12 <asp:BulletedList ID="uxList" DataSourceID="LinkData"
13 runat="server" DataTextField="Name" />
14 <asp:BulletedList ID="uxListStatic" ClientIDMode="Static"
15 DataSourceID="LinkData" runat="server" DataTextField="Name" />
16
17 <script type="text/javascript">
18 $(function() {
19 $("#uxList").append("<li>Red</li>");
20 $("#uxListStatic").append("<li>Brown</li>");
21 });
22 </script>
23 </asp:Content>

HTML输出如下:

1 <div>
2 <ul id="ctl00_ContentPlaceHolder1_uxList">
3 <li>Red</li><li>Blue</li><li>Yellow</li><li>Green</li>
4 </ul>
5 <ul id="uxListStatic">
6 <li>Red</li><li>Blue</li><li>Yellow</li><li>Green</li>
7 </ul>
8
9 <script type="text/javascript">
10 $(function() {
11 $("#uxListStatic").append("<li>Brown</li>");
12 });
13 </script>
14 </div>

浏览器中输出:

• Red
• Blue
• Yellow
• Green
• Red
• Blue
• Yellow
• Green
• Brown