ASP.NET 4.0配置文件中的ClientIDMode属性详解

2019-05-25 09:24:38王冬梅

可以看到GirdView里面的Label形成了诸如grd_Account_ctl02_Label1格式的ClientID,而这正是:父容器ID(grd_Account)+"_"+行号格式(ctl02)+"_"+控件自身ID(ClientID)这种格式生成的。

2,Static:

当控件的ClientIDMode选中为Static时,该控件的ClientID 值就是其本身设置的 ID 属性值,其ClientID值不会受到父容器控件的影响。 

比如我们把上面的代码稍作修改,将Label1的ClientIDMode属性改为Static:

<asp:GridView ID="grd_Account" runat="server" AllowPaging="True" 
  AutoGenerateColumns="False" 
  DataKeyNames="Account Number" DataSourceID="sds_account" Height="63px" 
  Width="676px" PageSize="5" >
  <Columns>
    <asp:TemplateField HeaderText="Account Number" Sort ="Account Number">
      <ItemTemplate>
        <asp:Label ID="Label1" runat="server" Text='<%# Bind("[Account Number]") %>' ClientIDMode="Static"></asp:Label>
      </ItemTemplate>        
    </asp:TemplateField>
  </Columns>
</asp:GridView>

运行后查看得到的HTML代码:

<table cellspacing="0" rules="all" border="1" id="grd_Account" style="height:63px;width:676px;border-collapse:collapse;">
  <tr>
    <th scope="col">Account Number</th>
  </tr><tr>
    <td>
      <span id="Label1">1060</span>
    </td>
  </tr><tr>
    <td>
      <span id="Label1">1200</span>
    </td>
  </tr><tr>
    <td>
      <span id="Label1">1510</span>
    </td>
  </tr>
</table>

看到了吗,GridView里每行的Label1的ClientID都以自身ID的值出现了,不会受到父级容器控件的ID影响,这样在前台使用JS时我们就能通控件本身的ID值找到我们想要的控件了。

此外使用Static后势必页面中会出现很多同名的控件ID,只要这些同名ID的控件处于页面的不同层次(比如某一容器控件的内部和外部就是不同层次)上那么就不会出现问题,但是如果页面同一层次上有多个同ID的控件,那么页面就会报错。

3,Inherit:

这个属性其实没什么好说的,如果控件的ClientIDMode选中为Inherit,那么表示该控件的ClientIDMode会使用父级容器控件的ClientIDMode值,如果父级容器控件的ClientIDMode也为Inherit,那么会使用更上层容器控件的ClientIDMode值,直到回溯到页面的ClientIDMode值为止,页面的ClientIDMode值默认为Predictable ,你可以在页面上的<%@ Page%>指令中对该值做更改。此外Inherit也是ASP.NET 4.0中所有控件的ClientIDMode属性的默认值。

4,Predictable:

首先我先说明下之所以最后写Predictable,是因为我发现控件的ClientIDMode为Predictable时生成ClientID的机制会非常复杂,要分好几个部分分别进行讨论,其中还有特殊情况,所以我在这里只能说尽量将我发现的Predictable生成ClientID的机制阐述清楚。