IBindableTemplate 介面

定義

提供一種方法給 DetailsView 以及 FormView 之類的 ASP.NET 資料繫結控制項,讓它們能夠自動繫結到樣板化內容區段內的 ASP.NET 資料來源控制項。

public interface class IBindableTemplate : System::Web::UI::ITemplate
public interface IBindableTemplate : System.Web.UI.ITemplate
type IBindableTemplate = interface
    interface ITemplate
Public Interface IBindableTemplate
Implements ITemplate
衍生
實作

範例

下列程式碼範例示範控制項如何 FormView 以宣告方式定義樣板化內容、系結至控制項所提供的 SqlDataSource 資料,以及顯示和編輯現有的記錄。 ASP.NET 剖析器會剖析樣板化內容,並在執行時間建立 IBindableTemplate 物件,以便透過單向 ASP.NET 資料系結語法, <%# Eval("fieldname") %> 將控制項中的值 SqlDataSource 系結至範本中定義的資料系結區域, () 和雙向資料系結語法 (<%# Bind("fieldname") %>) 。

重要

此控制項有一個文字方塊可接受使用者輸入,這是潛在的安全性威脅。 根據預設,ASP.NET Web 網頁會驗證使用者輸入未包含指令碼或 HTML 項目。 如需詳細資訊,請參閱 Script Exploits Overview (指令碼攻擊概觀)。


<%@ Page language="C#" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<script runat="server">

  void EmployeeFormView_ItemUpdating(Object sender, FormViewUpdateEventArgs e)
  {

    // Validate the field values entered by the user. This
    // example determines whether the user left any fields
    // empty. Use the NewValues property to access the new 
    // values entered by the user.
    ArrayList emptyFieldList = ValidateFields(e.NewValues);

    if (emptyFieldList.Count > 0)
    {

      // The user left some fields empty. Display an error message.
      
      // Use the Keys property to retrieve the key field value.
      String keyValue = e.Keys["EmployeeID"].ToString();

      MessageLabel.Text = "You must enter a value for each field of record " +
        keyValue + ".<br/>The following fields are missing:<br/><br/>";

      // Display the missing fields.
      foreach (String value in emptyFieldList)
      {
        // Use the OldValues property to access the original value
        // of a field.
        MessageLabel.Text += value + " - Original Value = " + 
          e.OldValues[value].ToString() + "<br />";
      }

      // Cancel the update operation.
      e.Cancel = true;

    }
    else
    {
      // The field values passed validation. Clear the
      // error message label.
      MessageLabel.Text = "";
    }

  }

  ArrayList ValidateFields(IOrderedDictionary list)
  {
    
    // Create an ArrayList object to store the
    // names of any empty fields.
    ArrayList emptyFieldList = new ArrayList();

    // Iterate though the field values entered by
    // the user and check for an empty field. Empty
    // fields contain a null value.
    foreach (DictionaryEntry entry in list)
    {
      if (entry.Value == String.Empty)
      {
        // Add the field name to the ArrayList object.
        emptyFieldList.Add(entry.Key.ToString());
      }
    }

    return emptyFieldList;
  }

  void EmployeeFormView_ModeChanging(Object sender, FormViewModeEventArgs e)
  {
    if (e.CancelingEdit)
    {
      // The user canceled the update operation.
      // Clear the error message label.
      MessageLabel.Text = "";
    }
  }

</script>

<html xmlns="http://www.w3.org/1999/xhtml" >
  <head runat="server">
    <title>FormView Example</title>
</head>
<body>
    <form id="form1" runat="server">
        
      <h3>FormView Example</h3>
                       
      <asp:formview id="EmployeeFormView"
        datasourceid="EmployeeSource"
        allowpaging="true"
        datakeynames="EmployeeID"
        headertext="Employee Record"
        emptydatatext="No employees found."
        onitemupdating="EmployeeFormView_ItemUpdating"
        onmodechanging="EmployeeFormView_ModeChanging"  
        runat="server">
        
        <headerstyle backcolor="CornFlowerBlue"
          forecolor="White"
          font-size="14"
          horizontalalign="Center"  
          wrap="false"/>
        <rowstyle backcolor="LightBlue"
          wrap="false"/>
        <pagerstyle backcolor="CornFlowerBlue"/>

        <itemtemplate>
          <table>
            <tr>
              <td rowspan="6">
                <asp:image id="EmployeeImage"
                  imageurl='<%# Eval("PhotoPath") %>'
                  alternatetext='<%# Eval("LastName") %>' 
                  runat="server"/>
              </td>
              <td colspan="2">
                    
              </td>
            </tr>
            <tr>
              <td>
                <b>Name:</b>
              </td>
              <td>
                <%# Eval("FirstName") %> <%# Eval("LastName") %>
              </td>
            </tr>
            <tr>
              <td>
                <b>Title:</b>
              </td>
              <td>
                <%# Eval("Title") %>
              </td>
            </tr>
            <tr>
              <td>
                <b>Hire Date:</b>                 
              </td>
              <td>
                <%# Eval("HireDate","{0:d}") %>
              </td>
            </tr>
            <tr style="height:150; vertical-align:top">
              <td>
                <b>Address:</b>
              </td>
              <td>
                <%# Eval("Address") %><br/>
                <%# Eval("City") %> <%# Eval("Region") %>
                <%# Eval("PostalCode") %><br/>
                <%# Eval("Country") %>   
              </td>
            </tr>
            <tr>
              <td colspan="2">
                <asp:linkbutton id="Edit"
                  text="Edit"
                  commandname="Edit"
                  runat="server"/> 
              </td>
            </tr>
          </table>       
        </itemtemplate>
        <edititemtemplate>
          <table>
            <tr>
              <td rowspan="6">
                <asp:image id="EmployeeEditImage"
                  imageurl='<%# Eval("PhotoPath") %>'
                  alternatetext='<%# Eval("LastName") %>' 
                  runat="server"/>
              </td>
              <td colspan="2">
                    
              </td>
            </tr>
            <tr>
              <td>
                <b>Name:</b>
              </td>
              <td>
                <asp:textbox id="FirstNameUpdateTextBox"
                  text='<%# Bind("FirstName") %>'
                  runat="server"/>
                <asp:textbox id="LastNameUpdateTextBox"
                  text='<%# Bind("LastName") %>'
                  runat="server"/>
              </td>
            </tr>
            <tr>
              <td>
                <b>Title:</b>
              </td>
              <td>
                <asp:textbox id="TitleUpdateTextBox"
                  text='<%# Bind("Title") %>'
                  runat="server"/> 
              </td>
            </tr>
            <tr>
              <td>
                <b>Hire Date:</b>                 
              </td>
              <td>
                <asp:textbox id="HireDateUpdateTextBox"
                  text='<%# Bind("HireDate", "{0:d}") %>'
                  runat="server"/>
              </td>
            </tr>
            <tr style="height:150; vertical-align:top">
              <td>
                <b>Address:</b>
              </td>
              <td>
                <asp:textbox id="AddressUpdateTextBox"
                  text='<%# Bind("Address") %>'
                  runat="server"/>
                <br/>
                <asp:textbox id="CityUpdateTextBox"
                  text='<%# Bind("City") %>'
                  runat="server"/> 
                <asp:textbox id="RegionUpdateTextBox"
                  text='<%# Bind("Region") %>'
                  width="40"
                  runat="server"/>
                <asp:textbox id="PostalCodeUpdateTextBox"
                  text='<%# Bind("PostalCode") %>'
                  width="60"
                  runat="server"/>
                <br/>
                <asp:textbox id="CountryUpdateTextBox"
                  text='<%# Bind("Country") %>'
                  runat="server"/> 
              </td>
            </tr>
            <tr>
              <td colspan="2">
                <asp:linkbutton id="UpdateButton"
                  text="Update"
                  commandname="Update"
                  runat="server"/>
                <asp:linkbutton id="CancelButton"
                  text="Cancel"
                  commandname="Cancel"
                  runat="server"/> 
              </td>
            </tr>
          </table>       
        </edititemtemplate>
          
        <pagersettings position="Bottom"
          mode="Numeric"/> 
                  
      </asp:formview>
      
      <br/><br/>
      
      <asp:label id="MessageLabel"
          forecolor="Red"
          runat="server"/>
          
      <!-- This example uses Microsoft SQL Server and connects  -->
      <!-- to the Northwind sample database. Use an ASP.NET     -->
      <!-- expression to retrieve the connection string value   -->
      <!-- from the Web.config file.                            -->
      <asp:sqldatasource id="EmployeeSource"
        selectcommand="Select [EmployeeID], [LastName], [FirstName], [Title], [Address], [City], [Region], [PostalCode], [Country], [HireDate], [PhotoPath] From [Employees]"
        updatecommand="Update [Employees] Set [LastName]=@LastName, [FirstName]=@FirstName, [Title]=@Title, [Address]=@Address, [City]=@City, [Region]=@Region, [PostalCode]=@PostalCode, [Country]=@Country Where [EmployeeID]=@EmployeeID"
        connectionstring="<%$ ConnectionStrings:NorthWindConnectionString%>" 
        runat="server"/>
            
    </form>
  </body>
</html>

<%@ Page language="VB" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<script runat="server">

  Sub EmployeeFormView_ItemUpdating(ByVal sender As Object, ByVal e As FormViewUpdateEventArgs) Handles EmployeeFormView.ItemUpdating
  
    ' Validate the field values entered by the user. This
    ' example determines whether the user left any fields
    ' empty. Use the NewValues property to access the new 
    ' values entered by the user.
        Dim emptyFieldList As ArrayList = ValidateFields(e.NewValues)

    If emptyFieldList.Count > 0 Then

      ' The user left some fields empty. Display an error message.
      
      ' Use the Keys property to retrieve the key field value.
      Dim keyValue As String = e.Keys("EmployeeID").ToString()

      MessageLabel.Text = "You must enter a value for each field of record " & _
        keyValue & ".<br/>The following fields are missing:<br/><br/>"

      ' Display the missing fields.
      Dim value As String
      For Each value In emptyFieldList
      
        ' Use the OldValues property to access the original value
        ' of a field.
        MessageLabel.Text &= value & " - Original Value = " & _
          e.OldValues(value).ToString() & "<br />"
        
      Next

      ' Cancel the update operation.
      e.Cancel = True

    Else
    
      ' The field values passed validation. Clear the
      ' error message label.
      MessageLabel.Text = ""
      
    End If

  End Sub

  Function ValidateFields(ByVal list As IOrderedDictionary) As ArrayList
    
    ' Create an ArrayList object to store the
    ' names of any empty fields.
    Dim emptyFieldList As New ArrayList()

    ' Iterate though the field values entered by
    ' the user and check for an empty field. Empty
    ' fields contain a null value.
    Dim entry As DictionaryEntry
    
    For Each entry In list
    
      If entry.Value Is String.Empty Then
      
        ' Add the field name to the ArrayList object.
        emptyFieldList.Add(entry.Key.ToString())
        
      End If
      
    Next

    Return emptyFieldList
  
  End Function
  
  Sub EmployeeFormView_ModeChanging(ByVal sender As Object, ByVal e As FormViewModeEventArgs) Handles EmployeeFormView.ModeChanging
  
    If e.CancelingEdit Then
      
      ' The user canceled the update operation.
      ' Clear the error message label.
      MessageLabel.Text = ""
    
    End If
    
  End Sub
  
</script>

<html xmlns="http://www.w3.org/1999/xhtml" >
  <head runat="server">
    <title>FormView Example</title>
</head>
<body>
    <form id="form1" runat="server">
        
      <h3>FormView Example</h3>
                       
      <asp:formview id="EmployeeFormView"
        datasourceid="EmployeeSource"
        allowpaging="true"
        datakeynames="EmployeeID"
        headertext="Employee Record"
        emptydatatext="No employees found."
        runat="server">
        
        <headerstyle backcolor="CornFlowerBlue"
          forecolor="White"
          font-size="14"
          horizontalalign="Center"  
          wrap="false"/>
        <rowstyle backcolor="LightBlue"
          wrap="false"/>
        <pagerstyle backcolor="CornFlowerBlue"/>

        <itemtemplate>
          <table>
            <tr>
              <td rowspan="6">
                <asp:image id="EmployeeImage"
                  imageurl='<%# Eval("PhotoPath") %>'
                  alternatetext='<%# Eval("LastName") %>' 
                  runat="server"/>
              </td>
              <td colspan="2">
                    
              </td>
            </tr>
            <tr>
              <td>
                <b>Name:</b>
              </td>
              <td>
                <%# Eval("FirstName") %> <%# Eval("LastName") %>
              </td>
            </tr>
            <tr>
              <td>
                <b>Title:</b>
              </td>
              <td>
                <%# Eval("Title") %>
              </td>
            </tr>
            <tr>
              <td>
                <b>Hire Date:</b>                 
              </td>
              <td>
                <%# Eval("HireDate","{0:d}") %>
              </td>
            </tr>
            <tr style="height:150; vertical-align:top">
              <td>
                <b>Address:</b>
              </td>
              <td>
                <%# Eval("Address") %><br/>
                <%# Eval("City") %> <%# Eval("Region") %>
                <%# Eval("PostalCode") %><br/>
                <%# Eval("Country") %>   
              </td>
            </tr>
            <tr>
              <td colspan="2">
                <asp:linkbutton id="Edit"
                  text="Edit"
                  commandname="Edit"
                  runat="server"/> 
              </td>
            </tr>
          </table>       
        </itemtemplate>
        <edititemtemplate>
          <table>
            <tr>
              <td rowspan="6">
                <asp:image id="EmployeeEditImage"
                  imageurl='<%# Eval("PhotoPath") %>'
                  alternatetext='<%# Eval("LastName") %>' 
                  runat="server"/>
              </td>
              <td colspan="2">
                    
              </td>
            </tr>
            <tr>
              <td>
                <b>Name:</b>
              </td>
              <td>
                <asp:textbox id="FirstNameUpdateTextBox"
                  text='<%# Bind("FirstName") %>'
                  runat="server"/>
                <asp:textbox id="LastNameUpdateTextBox"
                  text='<%# Bind("LastName") %>'
                  runat="server"/>
              </td>
            </tr>
            <tr>
              <td>
                <b>Title:</b>
              </td>
              <td>
                <asp:textbox id="TitleUpdateTextBox"
                  text='<%# Bind("Title") %>'
                  runat="server"/> 
              </td>
            </tr>
            <tr>
              <td>
                <b>Hire Date:</b>                 
              </td>
              <td>
                <asp:textbox id="HireDateUpdateTextBox"
                  text='<%# Bind("HireDate", "{0:d}") %>'
                  runat="server"/>
              </td>
            </tr>
            <tr style="height:150; vertical-align:top">
              <td>
                <b>Address:</b>
              </td>
              <td>
                <asp:textbox id="AddressUpdateTextBox"
                  text='<%# Bind("Address") %>'
                  runat="server"/>
                <br/>
                <asp:textbox id="CityUpdateTextBox"
                  text='<%# Bind("City") %>'
                  runat="server"/> 
                <asp:textbox id="RegionUpdateTextBox"
                  text='<%# Bind("Region") %>'
                  width="40"
                  runat="server"/>
                <asp:textbox id="PostalCodeUpdateTextBox"
                  text='<%# Bind("PostalCode") %>'
                  width="60"
                  runat="server"/>
                <br/>
                <asp:textbox id="CountryUpdateTextBox"
                  text='<%# Bind("Country") %>'
                  runat="server"/> 
              </td>
            </tr>
            <tr>
              <td colspan="2">
                <asp:linkbutton id="UpdateButton"
                  text="Update"
                  commandname="Update"
                  runat="server"/>
                <asp:linkbutton id="CancelButton"
                  text="Cancel"
                  commandname="Cancel"
                  runat="server"/> 
              </td>
            </tr>
          </table>       
        </edititemtemplate>
          
        <pagersettings position="Bottom"
          mode="Numeric"/> 
                  
      </asp:formview>
      
      <br/><br/>
      
      <asp:label id="MessageLabel"
          forecolor="Red"
          runat="server"/>
          
      <!-- This example uses Microsoft SQL Server and connects  -->
      <!-- to the Northwind sample database. Use an ASP.NET     -->
      <!-- expression to retrieve the connection string value   -->
      <!-- from the Web.config file.                            -->
      <asp:sqldatasource id="EmployeeSource"
        selectcommand="Select [EmployeeID], [LastName], [FirstName], [Title], [Address], [City], [Region], [PostalCode], [Country], [HireDate], [PhotoPath] From [Employees]"
        updatecommand="Update [Employees] Set [LastName]=@LastName, [FirstName]=@FirstName, [Title]=@Title, [Address]=@Address, [City]=@City, [Region]=@Region, [PostalCode]=@PostalCode, [Country]=@Country Where [EmployeeID]=@EmployeeID"
        connectionstring="<%$ ConnectionStrings:NorthWindConnectionString%>" 
        runat="server"/>
            
    </form>
  </body>
</html>

備註

IBindableTemplate 資料繫結控制項包含樣板化內容時,介面可讓您 ASP.NET 資料繫結控制項,例如 DetailsViewGridViewFormView ,系結至 ASP.NET 資料來源控制項所提供的資料,例如 ObjectDataSourceSqlDataSource

注意

頁面開發人員不會實作 IBindableTemplate 介面。 建立自訂資料繫結控制項的開發人員可能會在 和 ExtractRowValues 方法的 PerformDataBinding 實作中操作 IBindableTemplate 物件,但不會實作自己的 IBindableTemplate 物件。

這類 GridView 資料繫結控制項通常知道其子控制項樹狀結構,因此可以將值系結至它們、從中擷取值,並在資料系結控制項與資料來源控制項之間傳遞這些值,每當發生資料系結時。 不過,當頁面開發人員定義資料繫結控制項的樣板化內容時,父系資料繫結控制項看不到範本中的子控制項:父系可以轉譯子內容 (,因為控制項實際上會自行轉譯) ,但無法擷取這些子控制項的值以傳遞至相關聯的資料來源控制項更新, 插入或刪除作業。 在資料系結案例中,範本化內容對父系資料繫結控制項不透明。 語法 Bind 可讓資料繫結控制項從 實例內 IBindableTemplate 系結的控制項資料擷取值。

資料系結可以是單向或雙向。 (列舉定義這些系結方向 BindingDirection 。) 單向資料系結是以輸出方向執行的任何資料系結,從資料來源控制項到資料系結控制項;例如,任何資料讀取案例都牽涉到單向資料系結。 對於單向資料系結,您可以使用單向資料系結語法 (<%# Eval("fieldname") %>) 範本化內容內,不需要使用雙向 ASP.NET 資料系結語法。 雙向資料系結會以輸入方向描述資料系結,從資料繫結控制項到資料來源控制項。 使用 ASP.NET 資料系結和資料來源控制項的自動編輯、插入和刪除案例是雙向資料系結案例。 這些案例會使用雙向資料系結運算式 (<%# Bind("fieldname") %>) 。 介面 IBindableTemplate 和 ASP.NET 基礎結構支援 ASP.NET 資料來源控制項與樣板化內容之間的自動、宣告式雙向資料系結。 如需 ASP.NET 資料系結運算式和語法的詳細資訊,請參閱系結至資料庫和資料系結運算式概觀

資料繫結控制項的樣板化內容最常以宣告方式定義。 下表描述最常用來將樣板化資料系結至資料繫結控制項的程式。

資料繫結控制項 程序
DetailsView 資料繫結控制項會使用 DataSourceID 資料來源控制項的 屬性系結至資料,而樣板化內容則定義在 或 EditItemTemplate InsertItemTemplate 屬性中 ItemTemplate
GridView 資料繫結控制項會使用 DataSourceID 資料來源控制項的 屬性系結至資料,而樣板化內容則定義于 或 EditItemTemplate 屬性中 ItemTemplate 。 控制項 GridView 不支援插入作業。
FormView 資料繫結控制項會使用 DataSourceID 屬性系結至資料,而樣板化內容則定義于 ItemTemplateInsertItemTemplateEditItemTemplate 屬性或 物件中 TemplateField

DataListRepeater 控制項不支援自動雙向資料系結案例。

當範本內容系結至範本內的 ASP.NET 資料來源控制項時,ASP.NET 隱含地建立 IBindableTemplate 物件。 具體而言,當剖析器剖析使用 ASP.NET 資料系結語法的樣板化內容時,ASP.NET 剖析器會建立 類別的 CompiledBindableTemplateBuilder 實例,並包含支援資料系結的 ASP.NET Web 服務器控制項。 這些 ASP.NET 伺服器控制項會以 BindableAttribute 屬性標示。

介面 IBindableTemplate 會定義一個方法 ExtractValues 。 此方法是針對雙向資料系結所定義,因此資料繫結控制項可以自動從樣板化內容擷取名稱/值組,並在執行時間將配對傳遞至資料來源控制項。 若要讓自動資料系結成功,方法從 ExtractValues 樣板化內容擷取的功能變數名稱必須符合相關聯資料來源控制項中的參數名稱。 控制項開發人員只會在其實 ExtractRowValues 作中明確呼叫 ExtractValues 方法,或自訂資料繫結控制項的一些類似方法。

方法

ExtractValues(Control)

此方法若由某個類別實作出來時,會將樣板化內容中以雙向 ASP.NET 資料繫結語法繫結的值取出,組成一連串的名稱/值組。

InstantiateIn(Control)

當類別實作時,定義子控制項和樣板所屬的 Control 物件。 這些子控制項依次定義在內嵌樣板內。

(繼承來源 ITemplate)

適用於

另請參閱