資料繫結運算式語法
在網頁上呼叫 DataBind 方法時,資料繫結運算式便會在伺服控制項屬性和資料來源之間建立繫結。 您可以將資料繫結運算式包含在伺服器控制項開頭標記中屬性/值配組中值的那一端,或是網頁上的任何位置。
<tagprefix:tagname property="<%# data-binding expression %>"
runat="server" />
- or -
literal text <%# data-binding expression %>
參數
property
對它宣告這個資料繫結的控制項屬性。data-binding expression
符合<備註>章節中所列出之需求的任何運算式。
備註
所有的資料繫結運算式都必須包含在 <%# 和 %> 字元之間。
ASP.NET 支援階層式資料繫結模型,這種模型會建立伺服器控制項屬性與資料來源之間的繫結。 幾乎任何伺服器控制項屬性都可以與容納它的網頁,或是伺服器控制項之直接命名容器 (Container) 上的任何公用欄位或屬性產生繫結。
資料繫結運算式使用 Eval 和 Bind 方法將資料繫結至控制項,並將變更送回資料庫。 Eval 方法是一種靜態 (唯讀) 方法,會取得資料欄位的值,並且將其以字串的形式送回。 Bind 方法支援讀/寫功能,並具有擷取資料繫結控制項之值,以及將所有變更都送回資料庫的能力。
使用 XPath 和 XPathSelect 方法,以及 XPathBinder 類別,即可從 XmlDataSource 控制項繫結至 XML 資料。 如需詳細資訊,請參閱 XmlDataSource Web Server Control Overview。
範例
下列程式碼範例示範如何將資料繫結至 ASP.NET 伺服器控制項中的屬性。 當使用者從 DropDownList Web 伺服器選取某個狀態時,Label Web 伺服器控制項便會繫結至清單中的選取項目,並顯示選取的狀態。
<html>
<head>
<script language="C#" runat="server">
void SubmitBtn_Click(Object sender, EventArgs e) {
// Rather than explictly pulling out the variable from the StateList control
// and then manipulating a Label control, just call Page.DataBind.
// This will evaluate any <%# %> expressions within the page.
Page.DataBind();
}
</script>
</head>
<body>
<h3><font face="Verdana">Binding to a property of another server control</font></h3>
<form runat="server">
<asp:DropDownList id="StateList" runat="server">
<asp:ListItem>CA</asp:ListItem>
<asp:ListItem>IN</asp:ListItem>
<asp:ListItem>KS</asp:ListItem>
<asp:ListItem>MD</asp:ListItem>
<asp:ListItem>MI</asp:ListItem>
<asp:ListItem>OR</asp:ListItem>
<asp:ListItem>TN</asp:ListItem>
<asp:ListItem>UT</asp:ListItem>
</asp:DropDownList>
<asp:button Text="Submit" OnClick="SubmitBtn_Click" runat="server"/>
<p>
Selected State: <asp:label text='<%# StateList.SelectedItem.Text %>' runat="server"/>
</form>
</body>
</html>
<html>
<head>
<script language="VB" runat="server">
Sub SubmitBtn_Click(sender As Object, e As EventArgs)
' Rather than explictly pulling out the variable from the StateList control
' and then manipulating a Label control, just call Page.DataBind.
' This will evaluate any <%# %> expressions within the page.
Page.DataBind()
End Sub
</script>
</head>
<body>
<h3><font face="Verdana"> Binding to a property of another server control</font></h3>
<form runat="server">
<asp:DropDownList id="StateList" runat="server">
<asp:ListItem>CA</asp:ListItem>
<asp:ListItem>IN</asp:ListItem>
<asp:ListItem>KS</asp:ListItem>
<asp:ListItem>MD</asp:ListItem>
<asp:ListItem>MI</asp:ListItem>
<asp:ListItem>OR</asp:ListItem>
<asp:ListItem>TN</asp:ListItem>
<asp:ListItem>UT</asp:ListItem>
</asp:DropDownList>
<asp:button Text="Submit" OnClick="SubmitBtn_Click" runat="server"/>
<p>
Selected State: <asp:label text='<%# StateList.SelectedItem.Text %>' runat="server"/>
</form>
</body>
</html>
請參閱
參考
概念
Data-Binding Expressions Overview
Introduction to ASP.NET Web Pages