DataTypeAttribute DataTypeAttribute DataTypeAttribute DataTypeAttribute Class

定义

指定要与数据字段关联的其他类型的名称。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)]
[System.AttributeUsage(System.AttributeTargets.Property | System.AttributeTargets.Field, AllowMultiple=false)]
[System.AttributeUsage(System.AttributeTargets.Method | System.AttributeTargets.Property | System.AttributeTargets.Field | System.AttributeTargets.Parameter, AllowMultiple=false)]
public class DataTypeAttribute : System.ComponentModel.DataAnnotations.ValidationAttribute
type DataTypeAttribute = class
    inherit ValidationAttribute
Public Class DataTypeAttribute
Inherits ValidationAttribute
继承
派生
属性

示例

下面的示例使用DataTypeAttribute属性来自定义电子邮件地址的数据字段的显示。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枚举值。In the associated metadata class, it applies the DataTypeAttribute attribute to the EmailAddress data field by specifying the EmailAddress enumerated value. 这向 Text.ascx 字段模板表明,它应自定义显示内容的电子邮件地址。This indicates to the Text.ascx field template that it should customize the display of email addresses.

  • 它会修改自定义电子邮件地址数据字段显示在 Text.ascx 字段模板。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
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
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. 从选定的类型名称DataType枚举类型。The 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到数据字段的数据模型中以及通过指定来自的其他类型名称属性DataType枚举。You 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. 这是一种方式使用UIHintAttribute属性。This 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(DataType) DataTypeAttribute(DataType) DataTypeAttribute(DataType)

使用指定的类型名初始化 DataTypeAttribute 类的新实例。Initializes a new instance of the DataTypeAttribute class by using the specified type name.

DataTypeAttribute(String) DataTypeAttribute(String) DataTypeAttribute(String) DataTypeAttribute(String)

使用指定的字段模版名初始化 DataTypeAttribute 类的新实例。Initializes a new instance of the DataTypeAttribute class by using the specified field template name.

属性

CustomDataType CustomDataType CustomDataType CustomDataType

获取与数据字段关联的自定义字段模板的名称。Gets the name of custom field template that is associated with the data field.

DataType DataType DataType DataType

获取与数据字段关联的类型。Gets the type that is associated with the data field.

DisplayFormat DisplayFormat DisplayFormat DisplayFormat

获取数据字段的显示格式。Gets a data-field display format.

ErrorMessage ErrorMessage ErrorMessage ErrorMessage

获取或设置一条在验证失败的情况下与验证控件关联的错误消息。Gets or sets an error message to associate with a validation control if validation fails.

(Inherited from ValidationAttribute)
ErrorMessageResourceName ErrorMessageResourceName ErrorMessageResourceName ErrorMessageResourceName

获取或设置错误消息资源的名称,在验证失败的情况下,要使用该名称来查找 ErrorMessageResourceType 属性值。Gets or sets the error message resource name to use in order to look up the ErrorMessageResourceType property value if validation fails.

(Inherited from ValidationAttribute)
ErrorMessageResourceType ErrorMessageResourceType ErrorMessageResourceType ErrorMessageResourceType

获取或设置在验证失败的情况下用于查找错误消息的资源类型。Gets or sets the resource type to use for error-message lookup if validation fails.

(Inherited from ValidationAttribute)
ErrorMessageString ErrorMessageString ErrorMessageString ErrorMessageString

获取本地化的验证错误消息。Gets the localized validation error message.

(Inherited from ValidationAttribute)
RequiresValidationContext RequiresValidationContext RequiresValidationContext RequiresValidationContext

获取指示特性是否要求验证上下文的值。Gets a value that indicates whether the attribute requires validation context.

(Inherited from ValidationAttribute)
TypeId TypeId TypeId TypeId

在派生类中实现时,获取此 Attribute 的唯一标识符。When implemented in a derived class, gets a unique identifier for this Attribute.

(Inherited from Attribute)

方法

Equals(Object) Equals(Object) Equals(Object) Equals(Object)

返回一个值,该值指示此实例是否与指定的对象相等。Returns a value that indicates whether this instance is equal to a specified object.

(Inherited from Attribute)
FormatErrorMessage(String) FormatErrorMessage(String) FormatErrorMessage(String) FormatErrorMessage(String)

基于发生错误的数据字段对错误消息应用格式设置。Applies formatting to an error message, based on the data field where the error occurred.

(Inherited from ValidationAttribute)
GetDataTypeName() GetDataTypeName() GetDataTypeName() GetDataTypeName()

返回与数据字段关联的类型的名称。Returns the name of the type that is associated with the data field.

GetHashCode() GetHashCode() GetHashCode() GetHashCode()

返回此实例的哈希代码。Returns the hash code for this instance.

(Inherited from Attribute)
GetType() GetType() GetType() GetType()

获取当前实例的 TypeGets the Type of the current instance.

(Inherited from Object)
GetValidationResult(Object, ValidationContext) GetValidationResult(Object, ValidationContext) GetValidationResult(Object, ValidationContext) GetValidationResult(Object, ValidationContext)

检查指定的值对于当前的验证特性是否有效。Checks whether the specified value is valid with respect to the current validation attribute.

(Inherited from ValidationAttribute)
IsDefaultAttribute() IsDefaultAttribute() IsDefaultAttribute() IsDefaultAttribute()

在派生类中重写时,指示此实例的值是否是派生类的默认值。When overridden in a derived class, indicates whether the value of this instance is the default value for the derived class.

(Inherited from Attribute)
IsValid(Object) IsValid(Object) IsValid(Object) IsValid(Object)

检查数据字段的值是否有效。Checks that the value of the data field is valid.

IsValid(Object, ValidationContext) IsValid(Object, ValidationContext) IsValid(Object, ValidationContext) IsValid(Object, ValidationContext)

根据当前的验证特性来验证指定的值。Validates the specified value with respect to the current validation attribute.

(Inherited from ValidationAttribute)
Match(Object) Match(Object) Match(Object) Match(Object)

当在派生类中重写时,返回一个指示此实例是否等于指定对象的值。When overridden in a derived class, returns a value that indicates whether this instance equals a specified object.

(Inherited from Attribute)
MemberwiseClone() MemberwiseClone() MemberwiseClone() MemberwiseClone()

创建当前 Object 的浅表副本。Creates a shallow copy of the current Object.

(Inherited from Object)
ToString() ToString() ToString() ToString()

返回表示当前对象的字符串。Returns a string that represents the current object.

(Inherited from Object)
Validate(Object, String) Validate(Object, String) Validate(Object, String) Validate(Object, String)

验证指定的对象。Validates the specified object.

(Inherited from ValidationAttribute)
Validate(Object, ValidationContext) Validate(Object, ValidationContext) Validate(Object, ValidationContext) Validate(Object, ValidationContext)

验证指定的对象。Validates the specified object.

(Inherited from ValidationAttribute)

显式界面实现

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

将一组名称映射为对应的一组调度标识符。Maps a set of names to a corresponding set of dispatch identifiers.

(Inherited from Attribute)
_Attribute.GetTypeInfo(UInt32, UInt32, IntPtr) _Attribute.GetTypeInfo(UInt32, UInt32, IntPtr) _Attribute.GetTypeInfo(UInt32, UInt32, IntPtr) _Attribute.GetTypeInfo(UInt32, UInt32, IntPtr)

检索对象的类型信息,然后可以使用该信息获取接口的类型信息。Retrieves the type information for an object, which can be used to get the type information for an interface.

(Inherited from Attribute)
_Attribute.GetTypeInfoCount(UInt32) _Attribute.GetTypeInfoCount(UInt32) _Attribute.GetTypeInfoCount(UInt32) _Attribute.GetTypeInfoCount(UInt32)

检索对象提供的类型信息接口的数量(0 或 1)。Retrieves the number of type information interfaces that an object provides (either 0 or 1).

(Inherited from Attribute)
_Attribute.Invoke(UInt32, Guid, UInt32, Int16, IntPtr, IntPtr, IntPtr, IntPtr) _Attribute.Invoke(UInt32, Guid, UInt32, Int16, IntPtr, IntPtr, IntPtr, IntPtr) _Attribute.Invoke(UInt32, Guid, UInt32, Int16, IntPtr, IntPtr, IntPtr, IntPtr) _Attribute.Invoke(UInt32, Guid, UInt32, Int16, IntPtr, IntPtr, IntPtr, IntPtr)

提供对某一对象公开的属性和方法的访问。Provides access to properties and methods exposed by an object.

(Inherited from Attribute)

适用于

另请参阅