在ASP.NET中,在某些情况下,对于一些服务器控件[1],.NET会在客户端按一定的规律生成其客户端ID,这就造成控件的客户端ID和服务器端ID不一样,此时若要在客户端脚本中使用该控件,就必需先知道其客户端ID。幸好.NET为每个控件都提供了一个ClientID属性,该属性值即为控件在客户端的ID,下边是一个使用示例:
程序代码
<%@ Page Language="C#" %>
<%@ Import Namespace="System.Data" %>
<%@ Import Namespace="System.Data.SqlClient" %>
<script runat="server">
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
using (SqlConnection conn = new SqlConnection("server=(local);database=Northwind;user id=sa;password=sa;"))
{
using (SqlDataAdapter adapter = new SqlDataAdapter("Select TOP 10 * FROM Products", conn))
{
DataTable table = new DataTable();
adapter.Fill(table);
DataList1.DataSource = table;
DataList1.DataBind();
}
}
}
}
</script>
<html xmlns="
http://www.w3.org/1999/xhtml">
<head runat="server">
<title>ClientID示例-Mzwu.Com</title>
<script type="text/javascript">
function $(id){ return document.getElementById(id); }
function Show(id){ alert($(id).innerHTML); }
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:DataList ID="DataList1" runat="server">
<ItemTemplate>
<asp:Label ID="Label1" runat="server" Text='<%# Eval("ProductName") %>'></asp:Label>
<input type="button" value="button" onclick="Show('<%# ((Label)Container.FindControl("Label1")).ClientID%>')" />
</ItemTemplate>
</asp:DataList>
</div>
</form>
</body>
</html>
说明
[1].例如在用户控件中使用的控件,在DataList的ItemTemplate模板中使用的控件等等,.NET都会按一定的规律生成其客户端ID;
本文作者:Dnawo 来源: http://www.mzwu.com/
CIO之家 www.ciozj.com 微信公众号:imciow