DataTypeAttribute 類別

定義

指定要與資料欄位產生關聯的其他類型名稱。Specifies the name of an additional type to associate with a data field.

public ref class DataTypeAttribute : System::ComponentModel::DataAnnotations::ValidationAttribute
[System.AttributeUsage(System.AttributeTargets.Field | System.AttributeTargets.Method | System.AttributeTargets.Parameter | System.AttributeTargets.Property, AllowMultiple=false)]
public class DataTypeAttribute : System.ComponentModel.DataAnnotations.ValidationAttribute
[System.AttributeUsage(System.AttributeTargets.Field | System.AttributeTargets.Property, AllowMultiple=false)]
public class DataTypeAttribute : System.ComponentModel.DataAnnotations.ValidationAttribute
[<System.AttributeUsage(System.AttributeTargets.Field | System.AttributeTargets.Method | System.AttributeTargets.Parameter | System.AttributeTargets.Property, AllowMultiple=false)>]
type DataTypeAttribute = class
    inherit ValidationAttribute
[<System.AttributeUsage(System.AttributeTargets.Field | System.AttributeTargets.Property, AllowMultiple=false)>]
type DataTypeAttribute = class
    inherit ValidationAttribute
Public Class DataTypeAttribute
Inherits ValidationAttribute
繼承
衍生
屬性

範例

下列範例會使用 DataTypeAttribute 屬性來自訂 EmailAddress 資料欄位的顯示。The following example uses the DataTypeAttribute attribute to customize the display of the EmailAddress data field. 電子郵件地址會顯示為超連結,而不是簡單文字,動態資料會從內建資料類型推斷。The email addresses are shown as hyperlinks instead of as simple text, which is what Dynamic Data would infer from the intrinsic data type. 範例程式碼分為三個部分,並執行下列步驟:The example code is in three parts, and it performs the following steps:

  • 它會執行中繼資料部分類別和相關聯的中繼資料類別。It implements a metadata partial class and the associated metadata class.

  • 在相關聯的中繼資料類別中,它會藉 DataTypeAttribute 由指定列舉值,將屬性套用至 EmailAddress 資料欄位 EmailAddressIn the associated metadata class, it applies the DataTypeAttribute attribute to the EmailAddress data field by specifying the EmailAddress enumerated value. 這會向 [文字檔] 欄位範本指出它應該自訂電子郵件地址的顯示。This indicates to the Text.ascx field template that it should customize the display of email addresses.

  • 它會修改 [文字檔] 欄位範本,以自訂 EmailAddress 資料欄位的顯示。It modifies the Text.ascx field template to customize the display of the EmailAddress data fields.

using System;
using System.Web.DynamicData;
using System.ComponentModel.DataAnnotations;

[MetadataType(typeof(CustomerMetaData))]
public partial class Customer
{
}

public class CustomerMetaData
{

    // Add type information.
    [DataType(DataType.EmailAddress)]
    public object EmailAddress;
}

Imports System.Web.DynamicData
Imports System.ComponentModel.DataAnnotations

<MetadataType(GetType(CustomerMetadata))> _
Partial Public Class Customer


End Class

Public Class CustomerMetadata

    ' Add type information.
    <DataType(DataType.EmailAddress)> _
    Public EmailAddress As Object

End Class


<%@ Control Language="C#" 
CodeFile="Text.ascx.cs" Inherits="TextField" %>

<!-- Removed, evaluated in the code behind.
<%# FieldValueString %> --> 

<%@ Control Language="VB" 
  CodeFile="Text.ascx.vb" Inherits="TextField" %>

<!-- Removed, evaluated in the code behind.
<%# FieldValueString %> --> 


using System;
using System.Linq;
using System.Web.UI.WebControls;
using System.Web.DynamicData;
using System.ComponentModel.DataAnnotations;

public partial class TextField : 
    System.Web.DynamicData.FieldTemplateUserControl {

    protected override void OnDataBinding(EventArgs e)
    {
        base.OnDataBinding(e);
        bool processed = false;
        var metadata = MetadataAttributes.OfType
            <DataTypeAttribute>().FirstOrDefault();
        if (metadata != null)
        {
            if (metadata.DataType == DataType.EmailAddress)
            {
                if (!string.IsNullOrEmpty(FieldValueString))
                {
                    processed = true;
                    HyperLink hyperlink = new HyperLink();
                    hyperlink.Text = FieldValueString;
                    hyperlink.NavigateUrl = "mailto:" + FieldValueString;
                    Controls.Add(hyperlink);
                }
            }
        }
        if (!processed)
        {
            Literal literal = new Literal();
            literal.Text = FieldValueString;
            Controls.Add(literal);
        }
    }
}
Imports System.Linq
Imports System.Web.UI.WebControls
Imports System.Web.DynamicData
Imports System.ComponentModel.DataAnnotations

Partial Public Class TextField
    Inherits System.Web.DynamicData.FieldTemplateUserControl

    Protected Overloads Overrides Sub OnDataBinding(ByVal e As EventArgs)
        MyBase.OnDataBinding(e)
        Dim processed As Boolean = False
        Dim metadata As DataTypeAttribute = _
           MetadataAttributes.OfType(Of DataTypeAttribute)().FirstOrDefault()
        If metadata IsNot Nothing Then
            If metadata.DataType = DataType.EmailAddress Then
                If Not String.IsNullOrEmpty(FieldValueString) Then
                    processed = True
                    Dim hyperlink As New HyperLink()
                    hyperlink.Text = FieldValueString
                    hyperlink.NavigateUrl = "mailto:" + FieldValueString
                    Controls.Add(hyperlink)
                End If
            End If
        End If
        If Not processed Then
            Dim literal As New Literal()
            literal.Text = FieldValueString
            Controls.Add(literal)
        End If
    End Sub

End Class

若要編譯和執行範例程式碼,您需要下列各項:To compile and run the example code, you need the following:

  • 任何版本的 Visual Studio 2010 或更新版本。Any edition of Visual Studio 2010 or later.

  • AdventureWorksLT 範例資料庫。The AdventureWorksLT sample database. 如需有關如何下載及安裝 SQL Server 範例資料庫的詳細資訊,請參閱 Microsoft SQL Server 產品範例: GitHub 上的資料庫。For information about how to download and install the SQL Server sample database, see Microsoft SQL Server Product Samples: Database on GitHub. 確定您已針對您正在執行的 SQL Server 版本安裝正確版本的範例資料庫。Make sure that you install the correct version of the sample database for the version of SQL Server that you are running.

  • 資料驅動網站。A data-driven Web site. 這可讓您建立資料庫的資料內容,以及建立包含要自訂之資料欄位的類別。This enables you to create a data context for the database and to create the class that contains the data field to customize. 如需詳細資訊,請參閱Walkthrough: Creating a New Dynamic Data Web Site using ScaffoldingFor more information, see Walkthrough: Creating a New Dynamic Data Web Site using Scaffolding.

備註

DataTypeAttribute屬性可讓您使用比資料庫內建類型更明確的類型來標記欄位。The DataTypeAttribute attribute enables you to mark fields by using a type that is more specific than the database intrinsic type. 從列舉類型中選取了類型名稱 DataTypeThe type name is selected from the DataType enumeration type. 例如,包含電子郵件地址的字串資料欄位可以指定為 EmailAddress 類型。For example, a string data field that contains email addresses can be specified as the EmailAddress type. 這項資訊接著會由欄位範本存取,以修改資料欄位的處理方式。This information is then accessed by the field templates to modify how the data field is processed.

基於下列原因,您可以使用 DataTypeAttribute 屬性:You use the DataTypeAttribute attribute for the following reasons:

  • 提供資料欄位的其他類型資訊。To provide additional type information for a data field. 若要這麼做,請將 DataTypeAttribute 屬性套用至資料模型中的資料欄位,並指定列舉中的其他類型名稱 DataTypeYou do this by applying the DataTypeAttribute attribute to a data field in the data model and by specifying the additional type name from the DataType enumeration. 處理資料欄位的欄位範本可以存取這個額外的元資料類型資訊,以判斷如何處理欄位。The field template that processes the data field can access this additional metadata type information to determine how to process the field. 例如,文字欄位範本可以為內建類型為的電子郵件地址產生超連結 StringFor example, the text field template can generate hyperlinks for email addresses whose intrinsic type is String.

  • 將自訂欄位範本與資料欄位產生關聯。To associate a custom field template with a data field. 指定的自訂欄位範本接著將用來處理資料欄位。The specified custom field template will then be used to process the data field. 這是使用屬性的替代方法 UIHintAttributeThis is an alternative to using the UIHintAttribute attribute.

當您將 DataTypeAttribute 屬性套用至資料欄位時,必須執行下列動作:When you apply the DataTypeAttribute attribute to a data field you must do the following:

  • 遵循屬性使用規則。Follow the attribute usage rules.

  • 執行包含您要套用屬性之資料欄位的中繼資料類別。Implement the metadata class that contains the data fields to which you want to apply the attribute.

  • 適當地發出驗證錯誤。Issue validation errors as appropriate.

如需詳細資訊,請參閱 ASP.NET 動態資料指導方針For more information, see ASP.NET Dynamic Data Guidelines.

建構函式

DataTypeAttribute(DataType)

使用指定的型別名稱來初始化 DataTypeAttribute 類別的新執行個體。Initializes a new instance of the DataTypeAttribute class by using the specified type name.

DataTypeAttribute(String)

使用指定的欄位範本名稱,來初始化 DataTypeAttribute 類別的新執行個體。Initializes a new instance of the DataTypeAttribute class by using the specified field template name.

屬性

CustomDataType

取得與資料欄位相關聯的自訂欄位範本名稱。Gets the name of custom field template that is associated with the data field.

DataType

取得與資料欄位相關聯的型別。Gets the type that is associated with the data field.

DisplayFormat

取得資料欄位的顯示格式。Gets a data-field display format.

ErrorMessage

取得或設定錯誤訊息,此錯誤訊息會在驗證失敗時與驗證控制項產生關聯。Gets or sets an error message to associate with a validation control if validation fails.

(繼承來源 ValidationAttribute)
ErrorMessageResourceName

取得或設定要在驗證失敗時用來查閱 ErrorMessageResourceType 屬性值的錯誤訊息資源名稱。Gets or sets the error message resource name to use in order to look up the ErrorMessageResourceType property value if validation fails.

(繼承來源 ValidationAttribute)
ErrorMessageResourceType

取得或設定資源類型,此類型可在驗證失敗時用於查閱錯誤訊息。Gets or sets the resource type to use for error-message lookup if validation fails.

(繼承來源 ValidationAttribute)
ErrorMessageString

取得當地語系化的驗證錯誤訊息。Gets the localized validation error message.

(繼承來源 ValidationAttribute)
RequiresValidationContext

取得值,這個值表示屬性是否需要驗證內容。Gets a value that indicates whether the attribute requires validation context.

(繼承來源 ValidationAttribute)
TypeId

在衍生類別中實作時,取得這個 Attribute 的唯一識別碼。When implemented in a derived class, gets a unique identifier for this Attribute.

(繼承來源 Attribute)

方法

Equals(Object)

傳回值,這個值指出此執行個體是否與指定的物件相等。Returns a value that indicates whether this instance is equal to a specified object.

(繼承來源 Attribute)
FormatErrorMessage(String)

根據發生錯誤所在的資料欄位,將格式套用至錯誤訊息。Applies formatting to an error message, based on the data field where the error occurred.

(繼承來源 ValidationAttribute)
GetDataTypeName()

傳回與資料欄位相關聯的型別名稱。Returns the name of the type that is associated with the data field.

GetHashCode()

傳回這個執行個體的雜湊碼。Returns the hash code for this instance.

(繼承來源 Attribute)
GetType()

取得目前執行個體的 TypeGets the Type of the current instance.

(繼承來源 Object)
GetValidationResult(Object, ValidationContext)

檢查指定的值在目前的驗證屬性方面是否有效。Checks whether the specified value is valid with respect to the current validation attribute.

(繼承來源 ValidationAttribute)
IsDefaultAttribute()

在衍生類別中覆寫時,表示這個執行個體的值是衍生類別的預設值。When overridden in a derived class, indicates whether the value of this instance is the default value for the derived class.

(繼承來源 Attribute)
IsValid(Object)

檢查資料欄位的值是否有效。Checks that the value of the data field is valid.

IsValid(Object, ValidationContext)

根據目前的驗證屬性,驗證指定的值。Validates the specified value with respect to the current validation attribute.

(繼承來源 ValidationAttribute)
Match(Object)

在衍生類別中覆寫時,會傳回值,表示這個執行個體是否等於指定物件。When overridden in a derived class, returns a value that indicates whether this instance equals a specified object.

(繼承來源 Attribute)
MemberwiseClone()

建立目前 Object 的淺層複製。Creates a shallow copy of the current Object.

(繼承來源 Object)
ToString()

傳回代表目前物件的字串。Returns a string that represents the current object.

(繼承來源 Object)
Validate(Object, String)

驗證指定的物件。Validates the specified object.

(繼承來源 ValidationAttribute)
Validate(Object, ValidationContext)

驗證指定的物件。Validates the specified object.

(繼承來源 ValidationAttribute)

明確介面實作

_Attribute.GetIDsOfNames(Guid, IntPtr, UInt32, UInt32, IntPtr)

將一組名稱對應至一組對應的分派識別項 (Dispatch Identifier)。Maps a set of names to a corresponding set of dispatch identifiers.

(繼承來源 Attribute)
_Attribute.GetTypeInfo(UInt32, UInt32, IntPtr)

擷取物件的類型資訊,可以用來取得介面的類型資訊。Retrieves the type information for an object, which can be used to get the type information for an interface.

(繼承來源 Attribute)
_Attribute.GetTypeInfoCount(UInt32)

擷取物件提供的類型資訊介面數目 (0 或 1)。Retrieves the number of type information interfaces that an object provides (either 0 or 1).

(繼承來源 Attribute)
_Attribute.Invoke(UInt32, Guid, UInt32, Int16, IntPtr, IntPtr, IntPtr, IntPtr)

提供物件所公開的屬性和方法的存取權。Provides access to properties and methods exposed by an object.

(繼承來源 Attribute)

適用於

另請參閱