更新: 2008 年 7 月
ASP.NET Dynamic Data 可以該您自訂並且擴充對資料模型的資料驗證。本主題會介紹您可以如何透過下列方法,在資料模型中加入資料欄位驗證。
在欄位中套用動態資料的 System.ComponentModel.DataAnnotations 屬性,自訂個別資料欄位的驗證。這些屬性定義常用的驗證規則,例如範圍檢查及必填的欄位等。這個方法可以讓您只要透過極少的程式碼撰寫,便能使用預先定義的驗證檢查。想要對動態資料已經提供的項目上套用其他驗證,而且預設 System.ComponentModel.DataAnnotations 屬性已足夠支援所需的條件時,則應該使用這個方法。
注意事項:您也可以建立自訂驗證屬性。如此便可以擴充 System.ComponentModel.DataAnnotations 屬性所提的驗證。如果可用屬性不符合特定資料欄位的驗證要求時,這個作法就很實用。如需詳細資訊,請參閱 HOW TO:使用自訂屬性自訂資料模型中的資料欄位驗證。
覆寫處理資料欄位變更或處理對應事件的部分類別方法,從而自訂個別資料欄位的驗證。這個方法可以讓您新增個別欄位的驗證及商務邏輯。
覆寫 OnValidate 方法或處理 Validate 事件,從而自訂資料欄位的驗證。正在處理資料表中任一資料欄位時,便會呼叫這個方法。相較於新增個別欄位的驗證,這個方法更為常見。相同的驗證邏輯可以套用於多個資料欄位時,這個作法就很實用。這也可以讓您執行包含多個欄位的驗證檢查。
資料模型擲回的任一驗證例外狀況都會由 DynamicValidator 控制項攔截。如果頁面包含 DynamicValidator 控制項,頁面中便會顯示錯誤。
- 對於加入資料模型中的驗證檢查,必須建立可以擴充資料模型中資料表的部分類別。接著,您便可以將驗證檢查加入到部分類別。
執行這個功能的線上範例。
建立驗證的部分類別
必須先實作可以擴充資料模型的部分類別,才能夠在資料模型層中自訂驗證。這可以讓您執行下列作業:
利用屬性加入中繼資料資訊,藉此自訂驗證。
實作可以讓您建立自己的驗證邏輯的部分類別方法,藉此自訂驗證。
若要建立驗證的部分類別
在 [方案總管] 中,以滑鼠右鍵按一下 [App_Code] 資料夾,然後按一下 [加入新項目]。
請在 [Visual Studio 安裝的範本] 下方,按一下 [類別]。
在 [名稱] 方塊中,輸入想要在其中加入驗證之資料表的名稱。
類別名稱必須符合代表資料表的實體類別名稱。例如,如果您想要加入 Customers 資料表的驗證,在 Visual C# 中必須命名檔案 Customer.cs (在 Visual Basic 中則要命名 Customer.vb),然後再命名類別 Customer。
在 Visual Basic 中將 Partial 關鍵字加入類別定義,或在 Visual C# 中將 partial 關鍵字加入類別定義,使其成為部分類別。
以下範例示範更新的類別宣告。
public partial class Customer { }Partial Public Class Customer End Class如果要在 Visual C# 中建立類別,請先刪除預設的建構函式。
使用 Visual Basic 中的 Imports 關鍵字或 Visual C# 中的 using 關鍵字,加入對 System.Web.DynamicData 與 System.ComponentModel.DataAnnotations 命名空間的參考,如下範例所示:
using System.Web.DynamicData; using System.ComponentModel.DataAnnotations;Imports System.Web.DynamicData Imports System.ComponentModel.DataAnnotations在同一個檔案中,建立要做為關聯中繼資料類別的第二個類別。命名該類別時,只要名稱有效且尚未使用即可。
以下範例示範中繼資料類別宣告。
[C#]
public class CustomerMetadata { }Public Class CustomerMetadata End Class關聯的中繼資料類別會提供物件,您可以將驗證屬性套用到該物件。
將 MetadataTypeAttribute 屬性加入至部分類別定義。命名屬性參數時,請使用您於上一個步驟中所建立之關聯中繼資料類別的名稱。
下列範例示範加入屬性的部分類別定義。
[MetadataType(typeof(CustomerMetadata))] public partial class Customer { }<MetadataType(GetType(CustomerMetadata))> _ Partial Public Class Customer End Class
使用屬性來自訂驗證
本節示範如何使用動態資料 System.ComponentModel.DataAnnotations 屬性提供的預設驗證規則,從而自訂驗證。
若要使用驗證屬性來驗證特定資料欄位
在中繼資料類別中,建立名稱對應於要驗證之資料欄位的屬性或欄位。
將 System.ComponentModel.DataAnnotations 命名空間中的任一 屬性 (attribute) 套用到屬性 (Property)。
下列範例示範如何在關聯的中繼資料類別中,套用 System.ComponentModel.DataAnnotations.RequiredAttribute 屬性到 Title 資料欄位。如果使用者輸入空白字串,則 IsValid 方法會擲回驗證例外狀況並產生錯誤訊息。
注意事項:套用 RequiredAttribute 屬性時,您需要使用者輸入一個值,即使資料庫不需要這個值也是如此。
public class CustomerMetadata { [Required()] public object Title; }Public Class CustomerMetadata <Required()> _ Public Title As Object End Class
使用部分類別方法,藉此自訂個別資料欄位的驗證
本節說明如何覆寫處理個別資料欄位變更的部分類別方法,從而自訂驗證。這種類型的驗證可以該您建立自己的規則執行驗證,而不要使用實作於 System.ComponentModel.DataAnnotations 屬性中的內建動態資料驗證檢查。
若要使用部分類別方法來驗證特定資料欄位
覆寫這個部分類別方法來處理對資料欄位進行的變更。
加入您自訂的驗證邏輯。
下列範例示範如何覆寫 Customer 部分類別中的 OnTitleChanging 方法。當 Customer 資料表的 Title 欄位變更時,會呼叫這個方法。範例中的程式碼會檢查使用者輸入的新標題都是以大寫字母為開頭。如果資料沒有通過驗證,方法便會擲回例外狀況。要驗證的值會傳遞給方法做為唯一的參數。參數的型別必須符合要驗證之資料的資料型別。
注意事項:資料模型擲回的任一驗證例外狀況都會由 DynamicValidator 控制項攔截。如果頁面包含 DynamicValidator 控制項,頁面中便會顯示錯誤。
public partial class Customer { partial void OnTitleChanging(string value) { if (!Char.IsUpper(value[0])) { throw new ValidationException( "Title must start with an uppercase letter.");} } }Public Partial Class Customer Private Sub OnTitleChanging(ByVal value As String) If Not [Char].IsUpper(value(0)) Then Throw New ValidationException( _ "Title must start with an uppercase letter.") End If End Sub End Class
使用部分類別方法,藉此自訂所有資料欄位的驗證
本節說明如何覆寫處理資料表中任一資料欄位變更的部分類別方法,從而自訂驗證。這種類型的驗證可以該您建立自己的規則執行驗證,而不要使用實作於 System.ComponentModel.DataAnnotations 屬性中的內建動態資料驗證檢查。相同的驗證邏輯可以套用於多個資料欄位時,這個作法就很實用。這也可以讓您執行包含多個欄位的驗證檢查。
若要使用部分類別方法來驗證任一資料欄位
覆寫會於資料表中任一資料欄位發生變更時叫用的 OnValidate 部分類別方法。
加入您自訂的驗證邏輯。
以下範例將說明如何覆寫 OnValidate 方法。這段範例程式碼會檢查使用者輸入的名字和姓氏都是以大寫字母為開頭。如果資料沒有通過驗證,方法便會擲回例外狀況。
注意事項:資料模型擲回的任一驗證例外狀況都會由 DynamicValidator 控制項攔截。如果頁面包含 DynamicValidator 控制項,頁面中便會顯示錯誤。
partial void OnValidate( System.Data.Linq.ChangeAction action) { if (!Char.IsUpper(this._LastName[0]) || !Char.IsUpper(this._FirstName[0])) throw new ValidationException( "Name must start with an uppercase letter."); }Private Sub OnValidate(ByVal action As _ System.Data.Linq.ChangeAction) If Not [Char].IsUpper(Me._LastName(0)) OrElse _ Not [Char].IsUpper(Me._FirstName(0)) Then Throw New ValidationException( _ "Name must start with an uppercase letter.") End If End Sub
範例
範例會示範如何使用 RequiredAttribute 屬性驗證 Customer 資料表的 Title 資料。範例中會使用 OnValidate 部分類別方法,確認使用者在 Title、FirstName 與 LastName 資料欄位中輸入的值,都是以大寫字母開頭。範例也會使用 OnOderQtyChanging 部分類別方法,確認使用者在 SalesOrderDetails 資料表中 OrderQty 資料欄位輸入的值,都大於指定的最小值。
Imports System
Imports System.Collections.Generic
Imports System.Linq
Imports System.Web
Imports System.Web.DynamicData
Imports System.ComponentModel.DataAnnotations
<MetadataType(GetType(CustomerMetadata))> _
Partial Public Class Customer
Private Sub OnValidate(ByVal action As System.Data.Linq.ChangeAction)
If Not Char.IsUpper(Me._LastName(0)) _
OrElse Not Char.IsUpper(Me._FirstName(0)) _
OrElse Not Char.IsUpper(Me._Title(0)) Then
Throw New ValidationException( _
"Data value must start with an uppercase letter.")
End If
End Sub
End Class
Public Class CustomerMetadata
<Required()> _
Public Title As Object
End Class
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.DynamicData;
using System.ComponentModel.DataAnnotations;
[MetadataType(typeof(CustomerMetadata))]
public partial class Customer
{
partial void OnValidate(System.Data.Linq.ChangeAction action)
{
if (!char.IsUpper(this._LastName[0]) ||
!char.IsUpper(this._FirstName[0]) ||
!char.IsUpper(this._Title[0]))
throw new ValidationException(
"Data value must start with an uppercase letter.");
}
}
public class CustomerMetadata
{
[Required()]
public object Title;
}
Imports System
Imports System.Collections.Generic
Imports System.Linq
Imports System.Web
Imports System.Web.DynamicData
Imports System.ComponentModel.DataAnnotations
Partial Public Class SalesOrderDetail
Private Sub OnOrderQtyChanging(ByVal value As Short)
If value < 100 Then
Throw New ValidationException( _
"Quantity is less than the allowed minimum of 100.")
End If
End Sub
End Class
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.DynamicData;
using System.ComponentModel.DataAnnotations;
public partial class SalesOrderDetail
{
partial void OnOrderQtyChanging(short value)
{
if (value < 100)
{
throw new ValidationException(
"Quantity is less than the allowed minimum of 100.");
}
}
}
<%@ Page Language="VB"
AutoEventWireup="true" CodeFile="CustomValidation.aspx.vb"
Inherits="CustomValidation" %>
<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:DynamicValidator ID="DynamicValidator1" ControlToValidate="GridView2"
/>
<table>
<tr>
<td align="left" valign="top" style="font-weight:bold">
Customize Validation Using the Table OnValidate
</td>
<td>
<asp:GridView ID="GridView1"
DataSourceID="GridDataSource"
AutoGenerateColumns="false"
AutoGenerateEditButton="true"
AllowPaging="true"
PageSize="5"
AllowSorting="true">
<Columns>
<asp:DynamicField DataField="Title" />
<asp:DynamicField DataField="FirstName" />
<asp:DynamicField DataField="LastName" />
</Columns>
<EmptyDataTemplate>
There are currently no items in this table.
</EmptyDataTemplate>
</asp:GridView>
</td>
</tr>
<tr>
<td align="left" valign="top" style="font-weight:bold">
Customize Validation Using OnOrderQtyChanging
</td>
<td>
<asp:GridView ID="GridView2"
DataSourceID="GridDataSource2"
AutoGenerateColumns="false"
AutoGenerateEditButton="true"
AllowPaging="true"
PageSize="5"
AllowSorting="true">
<Columns>
<asp:DynamicField DataField="OrderQty" />
</Columns>
<EmptyDataTemplate>
There are currently no items in this table.
</EmptyDataTemplate>
</asp:GridView>
</td>
</tr>
</table>
</form>
<!-- Connect to the database -->
<asp:LinqDataSource ID="GridDataSource"
TableName="Customers" EnableUpdate="true"
ContextTypeName="AdventureWorksLTDataContext">
</asp:LinqDataSource>
<!-- Connect to the database -->
<asp:LinqDataSource ID="GridDataSource2"
TableName="SalesOrderDetails" EnableUpdate="true"
ContextTypeName="AdventureWorksLTDataContext">
</asp:LinqDataSource>
</body>
</html>
<%@ Page Language="C#"
AutoEventWireup="true" CodeFile="CustomValidation.aspx.cs"
Inherits="CustomValidation" %>
<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:DynamicValidator ID="DynamicValidator1" ControlToValidate="GridView2"
/>
<table>
<tr>
<td align="left" valign="top" style="font-weight:bold">
Customize Validation Using the Table OnValidate
</td>
<td>
<asp:GridView ID="GridView1"
DataSourceID="GridDataSource"
AutoGenerateColumns="false"
AutoGenerateEditButton="true"
AllowPaging="true"
PageSize="5"
AllowSorting="true">
<Columns>
<asp:DynamicField DataField="Title" />
<asp:DynamicField DataField="FirstName" />
<asp:DynamicField DataField="LastName" />
</Columns>
<EmptyDataTemplate>
There are currently no items in this table.
</EmptyDataTemplate>
</asp:GridView>
</td>
</tr>
<tr>
<td align="left" valign="top" style="font-weight:bold">
Customize Validation Using OnOrderQtyChanging
</td>
<td>
<asp:GridView ID="GridView2"
DataSourceID="GridDataSource2"
AutoGenerateColumns="false"
AutoGenerateEditButton="true"
AllowPaging="true"
PageSize="5"
AllowSorting="true">
<Columns>
<asp:DynamicField DataField="OrderQty" />
</Columns>
<EmptyDataTemplate>
There are currently no items in this table.
</EmptyDataTemplate>
</asp:GridView>
</td>
</tr>
</table>
</form>
<!-- Connect to the database -->
<asp:LinqDataSource ID="GridDataSource"
TableName="Customers" EnableUpdate="true"
ContextTypeName="AdventureWorksLTDataContext">
</asp:LinqDataSource>
<!-- Connect to the database -->
<asp:LinqDataSource ID="GridDataSource2"
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 CustomValidation
Inherits System.Web.UI.Page
Protected _table1 As MetaTable, _table2 As MetaTable
Protected Sub Page_Init(ByVal sender As Object, ByVal e As EventArgs)
' Register data controls with the data manager.
DynamicDataManager1.RegisterControl(GridView1)
DynamicDataManager1.RegisterControl(GridView2)
End Sub
Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)
' Get the table entities.
_table1 = GridDataSource.GetTable()
_table2 = GridDataSource2.GetTable()
' Assign title dynamically.
Title = String.Concat("Customize Validation of the ", _
_table1.Name, " and ", _table2.Name, " Tables")
End Sub
End Class
using System;
using System.Collections;
using System.Configuration;
using System.Web.DynamicData;
public partial class CustomValidation : System.Web.UI.Page
{
protected MetaTable _table1, _table2;
protected void Page_Init(object sender, EventArgs e)
{
// Register data controls with the data manager.
DynamicDataManager1.RegisterControl(GridView1);
DynamicDataManager1.RegisterControl(GridView2);
}
protected void Page_Load(object sender, EventArgs e)
{
// Get the table entities.
_table1 = GridDataSource.GetTable();
_table2 = GridDataSource2.GetTable();
// Assign title dynamically.
Title = string.Concat("Customize Validation of the ",
_table1.Name, " and ", _table2.Name, " Tables");
}
}
編譯程式碼
若要編譯這段範例程式碼,您需要下列項目:
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) 安裝版本正確的範例資料庫。
Dynamic Data 網站。這可以讓您建立資料庫的資料內容,並且建立包含可以自訂之資料欄位的類別與要覆寫的方法。如需詳細資訊,請參閱Walkthrough: Creating a New Dynamic Data Web Site Using Scaffolding。
請參閱
概念
參考
變更記錄
日期 |
記錄 |
原因 |
|---|---|---|
|
2008 年 7 月 |
加入主題。 |
SP1 功能變更。 |