給予翻譯建議
 
其他人的建议:

progress indicator
無其他建議。
按一下以給予評分及指教
MSDN
MSDN Library
Web 開發
ASP.NET
ASP.NET 4
全部折疊/全部展開 全部折疊
檢視內容: 並排檢視檢視內容: 並排檢視
.NET Framework 4 - ASP.NET
Data-Binding Expressions Overview

Data-binding syntax allows you to bind control property values to data and specify values for retrieving, updating, deleting, and inserting data.

Data-binding expressions are contained within <%# and %> delimiters and use the Eval and Bind functions. The Eval function is used to define one-way (read-only) binding. The Bind function is used for two-way (updatable) binding. In addition to calling Eval and Bind methods to perform data binding in a data-binding expression, you can call any publicly scoped code within the <%# and %> delimiters to execute that code and return a value during page processing.

Data-binding expressions are resolved when the DataBind method of a control or of the Page class is called. For controls such as the GridView, DetailsView, and FormView controls, data-binding expressions are resolved automatically during the control's PreRender event and you are not required to call the DataBind method explicitly.

The following code example shows the use of data-binding expressions with a FormView control in an ItemTemplate.

A Visual Studio project with source code is available to accompany this topic: Download.

Visual Basic
<asp:FormView ID="FormView1"
  DataSourceID="SqlDataSource1"
  DataKeyNames="ProductID"     
  RunAt="server">

  <ItemTemplate>
    <table>
      <tr>
        <td align="right"><b>Product ID:</b></td>       
        <td><%# Eval("ProductID") %></td>
      </tr>
      <tr>
        <td align="right"><b>Product Name:</b></td>     
        <td><%# Eval("ProductName") %></td>
      </tr>
      <tr>
        <td align="right"><b>Category ID:</b></td>      
        <td><%# Eval("CategoryID") %></td>
      </tr>
      <tr>
        <td align="right"><b>Quantity Per Unit:</b></td>
        <td><%# Eval("QuantityPerUnit") %></td>
      </tr>
      <tr>
        <td align="right"><b>Unit Price:</b></td>       
        <td><%# Eval("UnitPrice") %></td>
      </tr>
    </table>                 
  </ItemTemplate>                   
</asp:FormView>
C#
<asp:FormView ID="FormView1"
  DataSourceID="SqlDataSource1"
  DataKeyNames="ProductID"     
  RunAt="server">

  <ItemTemplate>
    <table>
      <tr>
        <td align="right"><b>Product ID:</b></td>       
        <td><%# Eval("ProductID") %></td>
      </tr>
      <tr>
        <td align="right"><b>Product Name:</b></td>     
        <td><%# Eval("ProductName") %></td>
      </tr>
      <tr>
        <td align="right"><b>Category ID:</b></td>      
        <td><%# Eval("CategoryID") %></td>
      </tr>
      <tr>
        <td align="right"><b>Quantity Per Unit:</b></td>
        <td><%# Eval("QuantityPerUnit") %></td>
      </tr>
      <tr>
        <td align="right"><b>Unit Price:</b></td>       
        <td><%# Eval("UnitPrice") %></td>
      </tr>
    </table>                 
  </ItemTemplate>                 
</asp:FormView>

Using the Eval Method

The Eval method evaluates late-bound data expressions in the templates of data-bound controls such as the GridView, DetailsView, and FormView controls. At run time, the Eval method calls the Eval method of the DataBinder object, referencing the current data item of the naming container. The naming container is generally the smallest part of the data-bound control that contains a whole record, such as a row in a GridView control. You can therefore use the Eval method only for binding inside templates of a data-bound control.

The Eval method takes the name of a data field and returns a string containing the value of that field from the current record in the data source. You can supply an optional second parameter to specify a format for the returned string. The string format parameter uses the syntax defined for the Format method of the String class.

Using the Bind Method

The Bind method has some similarities to the Eval method, but there are significant differences. Although you can retrieve the values of data-bound fields with the Bind method, as you can with the Eval method, the Bind method is also used when data can be modified.

In ASP.NET, data-bound controls such as the GridView, DetailsView, and FormView controls can automatically use the update, delete, and insert operations of a data source control. For example, if you have defined SQL Select, Insert, Delete, and Update statements for your data source control, using Bind in a GridView, DetailsView, or FormView control template enables the control to extract values from child controls in the template and pass them to the data source control. The data source control in turn performs the appropriate command for the database. For this reason, the Bind function is used inside the EditItemTemplate or InsertItemTemplate of a data-bound control.

The Bind method is typically used with input controls such as the TextBox control rendered by a GridView row in edit mode. When the data-bound control creates these input controls as part of its own rendering, it can extract the input values.

The Bind method takes the name of a data field to associate with the bound property, as shown in the following example:

Security noteSecurity Note

This example has a text box that accepts user input, which is a potential security threat. By default, ASP.NET Web pages validate that user input does not include script or HTML elements. For more information, see Script Exploits Overview.

<EditItemTemplate>
  <table>
    <tr>
      <td align=right>
        <b>Employee ID:</b>
      </td>
      <td>
        <%# Eval("EmployeeID") %>
      </td>
    </tr>
    <tr>
      <td align=right>
        <b>First Name:</b>
      </td>
      <td>
        <asp:TextBox ID="EditFirstNameTextBox" RunAt="Server"
          Text='<%# Bind("FirstName") %>' />
      </td>
    </tr>
    <tr>
      <td align=right>
        <b>Last Name:</b>
      </td>
      <td>
        <asp:TextBox ID="EditLastNameTextBox" RunAt="Server"
            Text='<%# Bind("LastName") %>'  />
      </td>
    </tr>
    <tr>
      <td colspan="2">
        <asp:LinkButton ID="UpdateButton" RunAt="server"
          Text="Update" CommandName="Update" />
        &nbsp;
        <asp:LinkButton ID="CancelUpdateButton" RunAt="server"
          Text="Cancel" CommandName="Cancel" />
      </td>
    </tr>
  </table>
</EditItemTemplate>

When the Update button for the row is clicked, the values of each control property bound using Bind syntax are extracted and passed to the data source control for the update operation.

Controls such as GridView, FormView, and DetailsView controls perform binding by calling the DataBind method implicitly when they are bound to a data source control using the DataSourceID property. However, there are situations in which you need to call the DataBind method explicitly.

One situation is if you have bound a control to a data source control using the DataSource property instead of the DataSourceID property. In that case, you need to call the DataBind method explicitly to perform data binding and resolve data-binding expressions.

Another situation is if you need to manually refresh the data in a data-bound control. Consider a page where you have two controls that display information from the same database (perhaps using different views). In that case, you might need to explicitly re-bind the control to data to keep the data display synchronized. For example, you might have a GridView control displaying a list of products and a DetailsView control that allows users to edit an individual product. Although the GridView and DetailsView controls display data from the same source, they are bound to different data source controls because they use different queries to get their data. A user might update a record using the DetailsView control, causing the update to be performed by the associated data source control. However, because the GridView control is bound to a different data source control, it will display old record values until the page is refreshed. Therefore, after the data is updated by the DetailsView control, you can call the DataBind method. This causes the GridView control to update its view as well by re-executing any data-binding expressions and publicly scoped code within the <%# and %> delimiters. As a result, the GridView control reflects the update made by the DetailsView control.

A common scenario with data-bound controls is to enable users to update or insert a value by selecting it from a lookup table using a DropDownList control or other list control. In that case, the lookup control is bound to a separate data source that returns the list of possible values, and the lookup control's selected value is bound to a field in the parent data-bound row.

You can add this functionality as follows. First, for the lookup control, you add a list control (a DropDownList or ListBox control) to a template in a data-bound control such as a GridView, DetailsView, or FormView control. You bind the SelectedValue property of the lookup control to the related field in the container control's data source. Then you set the lookup control's DataSourceID property to a data source control that retrieves the lookup values. You set the lookup control's DataTextField property to the field from the lookup table that contains the values to display, and set its DataValueField property to the field from the lookup table that contains the unique identifier for the lookup value, if applicable.

The following code example shows a DropDownList control that is included in the InsertItemTemplate template of a FormView control (this could also be an InsertItemTemplate template of a TemplateField included in the Fields property of a DetailsView control or the Columns property of a GridView control). The SelectedValue property of the DropDownList control uses the Bind method for two-way binding to the CategoryID field of the current row for the FormView control. The DataSourceID property of the DropDownList control is set to a separate data source control that retrieves the list of possible category names and IDs. The DataTextField property of the DropDownList control is set to the CategoryName field from the lookup data source so that a list of possible category names is displayed. The DataValueField property of the DropDownList control is set to the CategoryID field from the lookup data source for the related category name. When a user selects a category name from the list, the SelectedValue property of the DropDownList control is set to the category ID for the selected category name.

Visual Basic
<tr>
  <td align="right"><b>Category:</b></td>
  <td><asp:DropDownList ID="InsertCategoryDropDownList" 
                        SelectedValue='<%# Bind("CategoryID") %>' 
                        DataSourceID="CategoriesDataSource"
                        DataTextField="CategoryName"
                        DataValueField="CategoryID"
                        RunAt="Server" />
  </td>
</tr>
C#
<tr>
  <td align="right"><b>Category:</b></td>
  <td><asp:DropDownList ID="InsertCategoryDropDownList" 
                        SelectedValue='<%# Bind("CategoryID") %>' 
                        DataSourceID="CategoriesDataSource"
                        DataTextField="CategoryName"
                        DataValueField="CategoryID"
                        RunAt="Server" />
  </td>
</tr>

The same list control could be used in an edit item template as well.

.NET Framework 4 - ASP.NET
資料繫結運算式概觀

資料繫結語法可以讓您將控制項屬性值繫結至資料,並且指定擷取、更新、刪除和插入資料的值。

資料繫結運算式包含在 <%#%> 分隔符號中,並且使用 EvalBind 函式。 Eval 函式是用來定義單向 (唯讀) 繫結。 Bind 函式是用在雙向 (可以更新的) 繫結。 除了在資料繫結運算式中呼叫 EvalBind 方法以執行資料繫結以外,您也可以呼叫 <%#%> 分隔符號中的任何公開範圍程式碼,在網頁處理期間執行程式碼和傳回值。

當呼叫控制項或 Page 類別的 DataBind 方法時,就會解析資料繫結運算式。 針對像是 GridViewDetailsViewFormView 的控制項,在控制項的 PreRender 事件期間會自動解析資料繫結運算式,並且您不需要明確呼叫 DataBind 方法。

下列程式碼範例會示範在 ItemTemplate 中,搭配 FormView 控制項使用資料繫結運算式。

本主題隨附了一個含有原始程式碼的 Visual Studio 專案:下載 (英文)。

Visual Basic
<asp:FormView ID="FormView1"
  DataSourceID="SqlDataSource1"
  DataKeyNames="ProductID"     
  RunAt="server">

  <ItemTemplate>
    <table>
      <tr>
        <td align="right"><b>Product ID:</b></td>       
        <td><%# Eval("ProductID") %></td>
      </tr>
      <tr>
        <td align="right"><b>Product Name:</b></td>     
        <td><%# Eval("ProductName") %></td>
      </tr>
      <tr>
        <td align="right"><b>Category ID:</b></td>      
        <td><%# Eval("CategoryID") %></td>
      </tr>
      <tr>
        <td align="right"><b>Quantity Per Unit:</b></td>
        <td><%# Eval("QuantityPerUnit") %></td>
      </tr>
      <tr>
        <td align="right"><b>Unit Price:</b></td>       
        <td><%# Eval("UnitPrice") %></td>
      </tr>
    </table>                 
  </ItemTemplate>                   
</asp:FormView>
C#
<asp:FormView ID="FormView1"
  DataSourceID="SqlDataSource1"
  DataKeyNames="ProductID"     
  RunAt="server">

  <ItemTemplate>
    <table>
      <tr>
        <td align="right"><b>Product ID:</b></td>       
        <td><%# Eval("ProductID") %></td>
      </tr>
      <tr>
        <td align="right"><b>Product Name:</b></td>     
        <td><%# Eval("ProductName") %></td>
      </tr>
      <tr>
        <td align="right"><b>Category ID:</b></td>      
        <td><%# Eval("CategoryID") %></td>
      </tr>
      <tr>
        <td align="right"><b>Quantity Per Unit:</b></td>
        <td><%# Eval("QuantityPerUnit") %></td>
      </tr>
      <tr>
        <td align="right"><b>Unit Price:</b></td>       
        <td><%# Eval("UnitPrice") %></td>
      </tr>
    </table>                 
  </ItemTemplate>                 
</asp:FormView>

使用 Eval 方法

Eval 方法會評估資料繫結控制項範本 (例如 GridViewDetailsViewFormView 控制項) 中的晚期繫結資料運算式。 在執行階段,Eval 方法會參考命名容器目前的資料項目,呼叫 DataBinder 物件的 Eval 方法。 命名容器通常是包含整個記錄的資料繫結控制項的最小部分,例如 GridView 控制項中的資料列。 因此您可以在資料繫結控制項範本內進行繫結時才使用 Eval 方法。

Eval 方法會以資料欄位的名稱做為參數,並且回傳包含資料來源的目前資料錄欄位值的字串。 您可以提供選擇性的第二個參數以指定回傳字串的格式。 字串格式參數會使用為 String 類別之 Format 方法定義的語法。

使用 Bind 方法

Bind 方法在某些地方相似於 Eval 方法,但是有一些顯著性的差異。 雖然您可以像使用 Eval 方法一樣,使用 Bind 方法擷取資料繫結欄位的值,但是當資料可以修改時也會使用 Bind 方法。

在 ASP.NET 中,像是 GridViewDetailsViewFormView 的資料繫結控制項能夠自動使用資料來源控制項的更新、刪除和插入作業。 例如,如果您已經為資料來源控制項定義 SQL Select、Insert、Delete 和 Update 陳述式,在 GridViewDetailsViewFormView 控制項範本中使用 Bind 會讓控制項能夠從範本的子控制項擷取值,並將其傳遞給資料來源控制項。 然後資料來源控制項會執行適當的資料庫命令。 因此,Bind 函式會在資料繫結控制項的 EditItemTemplateInsertItemTemplate 中使用。

一般會搭配輸入控制項使用 Bind 方法,例如在編輯模式中 GridView 資料列呈現的 TextBox 控制項。 當資料繫結控制項建立這些輸入控制項當做自己呈現的一部分時,就能夠擷取輸入值。

Bind 方法會以資料欄位名稱做為參數,與繫結的屬性產生關聯,如同下列範例所示:

安全性注意事項安全性注意事項

這個範例有一個可接受使用者輸入的文字方塊,這可能會造成安全性威脅。 根據預設,ASP.NET Web 網頁會驗證該使用者的輸入內容中沒有包含指令碼或 HTML 項目。 如需詳細資訊,請參閱指令碼攻擊概觀

<EditItemTemplate>
  <table>
    <tr>
      <td align=right>
        <b>Employee ID:</b>
      </td>
      <td>
        <%# Eval("EmployeeID") %>
      </td>
    </tr>
    <tr>
      <td align=right>
        <b>First Name:</b>
      </td>
      <td>
        <asp:TextBox ID="EditFirstNameTextBox" RunAt="Server"
          Text='<%# Bind("FirstName") %>' />
      </td>
    </tr>
    <tr>
      <td align=right>
        <b>Last Name:</b>
      </td>
      <td>
        <asp:TextBox ID="EditLastNameTextBox" RunAt="Server"
            Text='<%# Bind("LastName") %>'  />
      </td>
    </tr>
    <tr>
      <td colspan="2">
        <asp:LinkButton ID="UpdateButton" RunAt="server"
          Text="Update" CommandName="Update" />
        &nbsp;
        <asp:LinkButton ID="CancelUpdateButton" RunAt="server"
          Text="Cancel" CommandName="Cancel" />
      </td>
    </tr>
  </table>
</EditItemTemplate>

當按下資料列的 Update 按鈕時,就會擷取每個使用 Bind 繫結之控制項屬性的值,然後傳遞給更新作業的資料來源控制項。

像是 GridViewFormViewDetailsView 的控制項,當使用 DataSourceID 屬性將其繫結至資料來源控制項時,會藉由隱含地呼叫 DataBind 方法執行繫結。 然而,在有些情形中您需要明確呼叫 DataBind 方法。

其中一種情形是如果您使用 DataSource 屬性,而不是 DataSourceID 屬性將控制項繫結至資料來源控制項。 在這種情況下,您需要明確呼叫 DataBind 方法執行資料繫結和解析資料繫結運算式。

另一種情形是如果您需要手動重新整理資料繫結控制項中的資料。 假設,在一個網頁上,有兩個顯示來自相同資料庫的資訊的控制項 (可能使用不同的檢視)。 在這種情況下,您需要明確將控制項重新繫結至資料以便保持資料顯示的同步。 例如,可能有顯示產品清單的 GridView 控制項,以及允許使用者編輯個別產品的 DetailsView 控制項。 雖然 GridViewDetailsView 控制項顯示相同來源的資料,但是因為其使用不同的查詢取得資料,所以是繫結至不同的資料來源控制項。 使用者可能會使用 DetailsView 控制項更新記錄,導致關聯的資料來源控制項執行更新。 然而,因為 GridView 控制項繫結至不同的資料來源控制項,所以在重新整理網頁之前都會顯示舊的記錄值。 因此,在 DetailsView 控制項更新資料後,您可以呼叫 DataBind 方法。 這也會導致 GridView 控制項藉由重新執行 <%#%> 分隔符號中的任何資料繫結運算式以及公開範圍程式碼,以便更新其檢視。 因此,GridView 控制項會反映 DetailsView 控制項所做的更新。

常見的資料繫結控制項案例,是讓使用者藉由使用 DropDownList 控制項或其他清單控制項,從查閱資料表 (Lookup Table) 中選取值,以便可以更新或插入值。 在這種狀況下,查閱控制項是繫結至可傳回可能值清單的個別資料來源,而查閱控制項的選取值則是繫結至父資料繫結資料列中的欄位。

您可以加入這個功能,如下所示: 首先,針對查閱控制項,您可以將清單控制項 (DropDownListListBox 控制項) 加入至資料繫結控制項 (例如 GridViewDetailsViewFormView 控制項) 中的樣板。 接著,把查閱控制項的 SelectedValue 屬性繫結至容器控制項的資料來源中的相關欄位。 然後,把查閱控制項的 DataSourceID 屬性設為可擷取查閱值的資料來源控制項。 如果可以的話,把查閱控制項的 DataTextField 屬性設為當中含有要顯示之值的查閱資料表欄位,並將其 DataValueField 屬性設為當中含有查閱值之唯一識別項的查閱資料表欄位。

下列程式碼範例示範的是 DropDownList 控制項,它包含在 FormView 控制項的 InsertItemTemplate 樣板 (這也可以是包含在 DetailsView 控制項之 Fields 屬性或 GridView 控制項之 Columns 屬性中的 TemplateFieldInsertItemTemplate 樣板)。 DropDownList 控制項的 SelectedValue 屬性會使用 Bind 方法的兩種繫結方式,對 FormView 控制項之目前資料列的 CategoryID 欄位進行繫結。 DropDownList 控制項的 DataSourceID 屬性是設為可擷取可能分類之名稱和 ID 清單的個別資料來源控制項。 DropDownList 控制項的 DataTextField 屬性是設為查閱資料來源中的 CategoryName 欄位,這樣才可以顯示可能分類之名稱清單。 DropDownList 控制項的 DataValueField 屬性是設為相關分類名稱之查閱資料來源中的 CategoryID 欄位。 當使用者選取清單中的分類名稱時,便會將 DropDownList 控制項的 SelectedValue 屬性設為所選分類名稱的分類 ID。

Visual Basic
<tr>
  <td align="right"><b>Category:</b></td>
  <td><asp:DropDownList ID="InsertCategoryDropDownList" 
                        SelectedValue='<%# Bind("CategoryID") %>' 
                        DataSourceID="CategoriesDataSource"
                        DataTextField="CategoryName"
                        DataValueField="CategoryID"
                        RunAt="Server" />
  </td>
</tr>
C#
<tr>
  <td align="right"><b>Category:</b></td>
  <td><asp:DropDownList ID="InsertCategoryDropDownList" 
                        SelectedValue='<%# Bind("CategoryID") %>' 
                        DataSourceID="CategoriesDataSource"
                        DataTextField="CategoryName"
                        DataValueField="CategoryID"
                        RunAt="Server" />
  </td>
</tr>

同一個清單控制項也可以一併在編輯項目樣板中使用。

社群內容   什麼是社群內容?
新增內容 RSS  註解
Processing
© 2012 Microsoft. 著作權所有,並保留一切權利。 使用規定 | 商標 | 隱私權聲明
Page view tracker