更新:2007 年 11 月
ASP.NET 動態資料包含欄位範本,用來呈現 UI 以便顯示和編輯資料欄位。您可以變更現有欄位範本,以及建立新的自訂欄位範本,以自訂 UI。
本主題將說明如何透過下列步驟,自訂資料欄位的外觀和行為:
將 UIHintAttribute 屬性套用至資料模型中的資料欄位。這麼做會指示「動態資料」使用自訂欄位範本來處理資料欄位。
建立對應的自訂欄位範本,用來呈現 UI 以便顯示和編輯資料欄位。
如本主題所示,您在資料層自訂資料欄位時,自訂內容會套用至整個網站。「動態資料」會使用自訂欄位範本來顯示和修改資料欄位,而不是使用根據資料欄位內建型別而選取的內建範本。
或者,您也可以將自訂內容限制在單一頁面。如需詳細資訊,請參閱 HOW TO:使用自訂頁面範本以自訂個別資料表的配置。
在資料層自訂資料欄位需要數個步驟。本主題中的程序將說明這個過程的每個步驟。
執行此功能的線上範例。
在資料模型中指定自訂欄位範本
本節說明將自訂欄位範本與資料欄位產生關聯的步驟。
若要將屬性套用至資料欄位
在 [方案總管] 中,以滑鼠右鍵按一下 [App_Code] 資料夾,然後按一下 [加入新項目]。
在 [Visual Studio 安裝的範本] 下方,按一下 [類別]。
在 [名稱] 方塊中,輸入資料庫資料表的名稱 (如資料模型中所定義),此資料庫資料表包含要顯示之自訂欄位範本的資料。
檔案名稱必須是代表資料表的實體類別名稱。例如,如果自訂欄位範本會顯示 SalesOrderDetail 資料表中的資料,則請將檔案命名為 SalesOrderDetail.cs 或 SalesOrderDetail.vb,並將類別命名為 SalesOrderDetail。您建立的類別檔案也會包含關聯類別,可以讓您將屬性套用至資料欄位。
在 Visual Basic 中將 Partial 關鍵字加入類別定義,或在 Visual C# 中將 partial 關鍵字加入類別定義,使其成為部分類別。如果您使用的是 Visual C#,請刪除預設的建構函式。
使用 Imports 關鍵字 (適用於 Visual Basic) 或 using 關鍵字 (適用於 Visual C#),匯入 System.Web.DynamicData 和 System.ComponentModel.DataAnnotations 命名空間,如下列範例所示:
using System.Web.DynamicData; using System.ComponentModel.DataAnnotations;Imports System.Web.DynamicData Imports System.ComponentModel.DataAnnotations在您於步驟 1 至 3 所建立的類別檔案中,建立另一個部分類別,做為關聯的中繼資料類別。您可以使用任何名稱做為類別名稱。
在下列範例中,會示範如何建立 SalesOrderDetail 欄位的關聯中繼資料類別。
public partial class SalesOrderDetailMetadata { }Partial Public Class SalesOrderDetailMetadata End Class將 MetadataTypeAttribute 屬性加入至資料表的部分類別定義。針對屬性的參數,請指定您在上一個步驟所建立之中繼資料類別的名稱。
在下列範例中,會示範如何套用屬性,以將部分 SalesOrderDetail 類別連接至其關聯的中繼資料類別。
[MetadataType(typeof(SalesOrderDetailMetadata))] public partial class SalesOrderDetail { }<MetadataType(GetType(SalesOrderDetailMetadata))> _ Partial Public Class SalesOrderDetail End Class在關聯的中繼資料類別中,建立一個公用屬性 (Property),其名稱符合您要自訂的資料欄位。
將 UIHintAttribute 屬性 (Attribute) 套用至該屬性 (Property),指定用於顯示和編輯之自訂欄位範本的名稱。
Object 型別是當做中繼資料類別中的預留位置型別,用來代表資料欄位。「動態資料」會在執行階段從資料模型推斷實際型別。
public partial class SalesOrderDetailMetadata { [UIHint("CustomFieldTemplate")] public object OrderQty; }Partial Public Class SalesOrderDetailMetadata <UIHint("CustomFieldTemplate")> _ Public OrderQty As Object End Class儲存並關閉類別檔案。
建立自訂欄位範本
欄位範本是使用者控制項,動態資料會利用這些控制項來呈現顯示與編輯資料的 UI。本節說明的步驟,可建立自訂欄位範本用來呈現 UI 以顯示資料欄位。
若要建立用於顯示的自訂欄位範本
在 [方案總管] 中,以滑鼠右鍵按一下 [DynamicData\FieldTemplates] 資料夾,然後按一下 [加入新項目]。
在 [Visual Studio 安裝的範本] 下方,按一下 [Dynamic Data 欄位]。
在 [名稱] 方塊中,輸入自訂欄位範本的名稱。任何尚未使用的名稱都可以使用。同時,請務必選取 [將程式碼置於個別檔案中] 方塊。
按一下 [加入]。
Visual Studio 隨即建立兩個欄位範本,一個用於顯示,一個用於編輯。例如,如果您輸入的名稱是 CustomFieldTemplate.ascx,則 Visual Studio 會建立 CustomFieldTemplate.ascx 和 CustomFieldTemplate_Edit.ascx。第一個範本會呈現用於顯示資料欄位的 UI,第二個範本則呈現用於編輯資料欄位的 UI。
如果您要自訂資料欄位的顯示方式,請開啟顯示使用者控制項檔案,並加入您的自訂內容。
在下列範例中,會示範用於顯示資料的自訂欄位範本。在範例中,Literal 控制項 (「Dynamic Data 欄位」範本中預設已提供) 會被 Label 控制項取代,後者的 Text 屬性設定為目前欄位值字串。您可以使用 FieldValueString 屬性存取資料欄位的值。
<asp:Label id="Label1" Text='<%# FieldValueString %>'> </asp:Label>如果需要自訂,請開啟顯示欄位範本的程式碼後置 (Code-Behind) 的檔案,並加入您的自訂內容。
在下列範例中,會示範如何使用您在標記中進行的變更 (如上一個步驟所示) 來同步 (Synchronize) 程式碼。在程式碼中,Literal1 識別項被取代為 Label1 識別項,以便支援用於顯示的 UI 自訂內容。
public override Control DataControl { get {return Label1;} }Public Overrides ReadOnly Property DataControl() As Control Get Return Label1 End Get End Property覆寫欄位範本的 OnDataBinding 方法,並加入程式碼以自訂資料欄位顯示。
在此方法中,您可以從控制項的 FieldValue 屬性取得目前資料欄位的值然後自訂顯示,如下列範例所示。
protected override void OnDataBinding(EventArgs e) { if (currentQty < min) { Label1.ForeColor = System.Drawing.Color.Red; Label1.Font.Bold = true; } else if (currentQty > max) { Label1.ForeColor = System.Drawing.Color.Blue; Label1.Font.Bold = true; } } }Protected Overloads Overrides Sub OnDataBinding( _ ByVal e As EventArgs) If currentQty < min Then Label1.ForeColor = System.Drawing.Color.Red Label1.Font.Bold = True ElseIf currentQty > max Then Label1.ForeColor = System.Drawing.Color.Blue Label1.Font.Bold = True End If End If End Sub
下一個程序說明的步驟,可建立自訂欄位範本用來呈現 UI 以編輯資料欄位。
若要建立用於編輯的自訂欄位範本
開啟名稱結尾為 _Edit 的自訂欄位範本,然後加入您的自訂內容。
在下列範例中,會示範加入了 CustomValidator 控制項 (一般參考) 控制項的標記,當使用者輸入的資料無效時,便會顯示自訂警告訊息。例如,資料欄位值超出欄位範本中定義的特定限制,就會顯示訊息。此範例會將驗證程式的 Display 屬性 (Property) 設定為 "Dynamic",如此只有驗證失敗時才會顯示驗證控制項。程式碼會將 ControlToValidate 屬性 (Attribute) 設定為要驗證之控制項的 ID,也會將 OnServerValidate 屬性 (Attribute) 設定為驗證事件之處理常式的名稱。
<asp:CustomValidator id="CustomValidator1" ControlToValidate="TextBox1" Display="Dynamic" OnServerValidate="CustomValidation" />儲存並關閉使用者控制項檔案。
如果需要自訂,請開啟編輯欄位範本的程式碼後置檔案,並加入您的自訂內容。
在下列範例中,會示範如何建立 CustomValidator 控制項的伺服端程式碼。程式碼會比較使用者輸入的值和某些臨界值,如果資料不在容許範圍內,便會顯示錯誤訊息。
protected void CustomValidation(object source, ServerValidateEventArgs args) { // Check if the input is in the allowed range. bool result = CheckRange(intUnits); // Return result. args.IsValid = result; }Protected Sub CustomValidation( _ ByVal source As Object, ByVal args As ServerValidateEventArgs) 'Check if the value is in the allowed range. Dim result As Boolean = CheckRange(intUnits) 'Return result. args.IsValid = result End Sub
範例
在這個範例中,會示範資料模型的用法,以自訂要呈現的 UI,用以顯示和編輯 SalesOrderDetail 資料表的 OrderQty 資料欄位。
CustomFieldTemplate.ascx 欄位範本會顯示訂單數量,如果該值小於警告臨界值下限,則會使用紅色前景。如果該值大於警告臨界值上限,則會使用藍色前景。
CustomFieldTemplate_Edit.ascx 欄位範本會檢查使用者輸入的 OrderQty 值是否符合範圍限制。如果使用者輸入的值不在容許範圍內,則會顯示自訂錯誤訊息。
<%@ Page Language="VB"
AutoEventWireup="true" CodeFile="CustomAppearanceBehavior.aspx.vb"
Inherits="CustomAppearanceBehavior" %>
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" >
<title></title>
<link href="~/Site.css" rel="stylesheet" type="text/css" />
</head>
<body>
<h2>Example: <%=Title%></h2>
<!-- Enable dynamic behavior. The GridView must be
registered with the manager. See code-behind file. -->
<asp:DynamicDataManager ID="DynamicDataManager1"
AutoLoadForeignKeys="true" />
<form id="form1" >
<!-- Capture validation exceptions -->
<asp:DynamicValidator ID="ValidatorID" ControlToValidate="GridView1"
/>
<asp:GridView ID="GridView1"
DataSourceID="GridDataSource"
AutoGenerateColumns="false"
AutoGenerateEditButton="true"
AllowPaging="true"
PageSize="10"
AllowSorting="true">
<Columns>
<asp:DynamicField DataField="OrderQty" />
<asp:DynamicField DataField="UnitPrice" />
<asp:DynamicField DataField="ModifiedDate" />
</Columns>
<EmptyDataTemplate>
There are currently no items in this table.
</EmptyDataTemplate>
</asp:GridView>
</form>
<!-- Connect to the database -->
<asp:LinqDataSource ID="GridDataSource"
TableName="SalesOrderDetails" EnableUpdate="true"
ContextTypeName="AdventureWorksLTDataContext">
</asp:LinqDataSource>
</body>
</html>
<%@ Page Language="C#"
AutoEventWireup="true" CodeFile="CustomAppearanceBehavior.aspx.cs"
Inherits="CustomAppearanceBehavior" %>
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" >
<title></title>
<link href="~/Site.css" rel="stylesheet" type="text/css" />
</head>
<body>
<h2>Example: <%=Title%></h2>
<!-- Enable dynamic behavior. The GridView must be
registered with the manager. See code-behind file. -->
<asp:DynamicDataManager ID="DynamicDataManager1"
AutoLoadForeignKeys="true" />
<form id="form1" >
<!-- Capture validation exceptions -->
<asp:DynamicValidator ID="ValidatorID" ControlToValidate="GridView1"
/>
<asp:GridView ID="GridView1"
DataSourceID="GridDataSource"
AutoGenerateColumns="false"
AutoGenerateEditButton="true"
AllowPaging="true"
PageSize="10"
AllowSorting="true">
<Columns>
<asp:DynamicField DataField="OrderQty" />
<asp:DynamicField DataField="UnitPrice" />
<asp:DynamicField DataField="ModifiedDate" />
</Columns>
<EmptyDataTemplate>
There are currently no items in this table.
</EmptyDataTemplate>
</asp:GridView>
</form>
<!-- Connect to the database -->
<asp:LinqDataSource ID="GridDataSource"
TableName="SalesOrderDetails" EnableUpdate="true"
ContextTypeName="AdventureWorksLTDataContext">
</asp:LinqDataSource>
</body>
</html>
Imports System
Imports System.Collections
Imports System.Configuration
Imports System.Web.DynamicData
Partial Public Class CustomAppearanceBehavior
Inherits System.Web.UI.Page
Protected _table As MetaTable
Protected Sub Page_Init(ByVal sender As Object, ByVal e As EventArgs)
' Register control with the data manager.
DynamicDataManager1.RegisterControl(GridView1)
End Sub
Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)
' Get the table entity.
_table = GridDataSource.GetTable()
' Assign title dynamically.
Title = String.Concat( _
"Customize Appearance and Behavior of the ", _
_table.Columns(2).DisplayName, " Data Field")
End Sub
End Class
using System;
using System.Collections;
using System.Configuration;
using System.Web.DynamicData;
public partial class CustomAppearanceBehavior : System.Web.UI.Page
{
protected MetaTable _table;
protected void Page_Init(object sender, EventArgs e)
{
// Register control with the data manager.
DynamicDataManager1.RegisterControl(GridView1);
}
protected void Page_Load(object sender, EventArgs e)
{
// Get the table entity.
_table = GridDataSource.GetTable();
// Assign title dynamically.
Title = string.Concat("Customize Appearance and Behavior of the ",
_table.Columns[2].DisplayName, " Data Field");
}
}
編譯程式碼
若要編譯範例程式碼,您需要下列各項:
Microsoft Visual Studio 2008 Service Pack 1 或 Visual Web Developer 2008 Express 版 Service Pack 1。
AdventureWorksLT 範例資料庫。如需下載並安裝 SQL Server 範例資料庫,請參閱 CodePlex 網站上的 Microsoft SQL Server 產品範例:資料庫 (英文)。請確認已配合您所執行的 SQL Server 版本 (Microsoft SQL Server 2005 或 Microsoft SQL Server 2008) 安裝版本正確的範例資料庫。
動態資料驅動型網站。這樣可讓您為資料庫建立資料內容,以及建立包含要自訂之資料欄位的類別。如需詳細資訊,請參閱Walkthrough: Creating a New Dynamic Data Web Site using Scaffolding。