DisplayFormatAttribute Classe
Definição
Especifica como os campos de dados são exibidos e formatados por Dados Dinâmicos do ASP.NET.Specifies how data fields are displayed and formatted by ASP.NET Dynamic Data.
public ref class DisplayFormatAttribute : Attribute
[System.AttributeUsage(System.AttributeTargets.Field | System.AttributeTargets.Property, AllowMultiple=false)]
public class DisplayFormatAttribute : Attribute
[<System.AttributeUsage(System.AttributeTargets.Field | System.AttributeTargets.Property, AllowMultiple=false)>]
type DisplayFormatAttribute = class
inherit Attribute
Public Class DisplayFormatAttribute
Inherits Attribute
- Herança
- Atributos
Exemplos
Consulte um exemplo online desse recurso: executar.See an online example of this feature: Run.
O exemplo a seguir mostra como usar o DisplayFormatAttribute para personalizar a formatação de um campo de dados.The following example shows how to use the DisplayFormatAttribute to customize formatting for a data field. O exemplo executa as seguintes etapas:The example performs the following steps:
Implementa uma classe parcial de metadados e uma classe de metadados associada.Implements a metadata partial class and an associated metadata class.
Na classe de metadados associada, ele aplica o DisplayFormatAttribute atributo para especificar os seguintes resultados:In the associated metadata class, it applies the DisplayFormatAttribute attribute to specify the following results:
Exibe o texto "[NULL]" quando um campo de dados está vazio.Display the text "[Null]" when a data field is empty.
Exibir dados de moeda no formato de moeda específico da localidade.Display currency data in locale specific currency format.
Exibir informações de data em formato curto (mm/dd/aa).Display date information in short format (mm/dd/yy). Esse formato também se aplica ao modo de edição.This format also applies in edit mode.
using System;
using System.Web.DynamicData;
using System.ComponentModel.DataAnnotations;
[MetadataType(typeof(ProductMetaData))]
public partial class Product
{
}
public class ProductMetaData
{
// Applying DisplayFormatAttribute
// Display the text [Null] when the data field is empty.
// Also, convert empty string to null for storing.
[DisplayFormat(ConvertEmptyStringToNull = true, NullDisplayText = "[Null]")]
public object Size;
// Display currency data field in the format $1,345.50.
[DisplayFormat(DataFormatString="{0:C}")]
public object StandardCost;
// Display date data field in the short format 11/12/08.
// Also, apply format in edit mode.
[DisplayFormat(ApplyFormatInEditMode=true, DataFormatString = "{0:d}")]
public object SellStartDate;
}
Imports System.Web.DynamicData
Imports System.ComponentModel.DataAnnotations
<MetadataType(GetType(ProductMetaData))> _
Partial Public Class Product
End Class
Public Class ProductMetaData
' Applying DisplayFormatAttribute
' Display the text [Null] when the data field is empty.
' Also, convert empty string to null for storing.
<DisplayFormat(ConvertEmptyStringToNull:=True, NullDisplayText:="[Null]")> _
Public Size As Object
' Display currency data field in the format such as $1,345.50.
<DisplayFormat(DataFormatString:="{0:C}")> _
Public StandardCost As Object
' Display date data field in the short format such as 11/12/08.
' Also, apply format in edit mode.
<DisplayFormat(ApplyFormatInEditMode:=True, DataFormatString:="{0:d}")> _
Public SellStartDate As Object
End Class
Para compilar o exemplo, você precisa do seguinte:To compile the example, you need the following:
Qualquer edição do Visual Studio 2010 ou posterior.Any edition of Visual Studio 2010 or later.
O banco de dados de exemplo AdventureWorksLT.The AdventureWorksLT sample database. Para obter informações sobre como baixar e instalar o SQL Server banco de dados de exemplo, consulte Microsoft SQL Server exemplos de produtos: banco de dados no github.For information about how to download and install the SQL Server sample database, see Microsoft SQL Server Product Samples: Database on GitHub. Certifique-se de instalar a versão correta do banco de dados de exemplo para a versão do SQL Server que você está executando.Make sure that you install the correct version of the sample database for the version of SQL Server that you are running.
Um site controlado por dados.A data-driven Web site. Isso permite que você crie um contexto de dados para o Database e a classe que contém o campo de dados a ser personalizado.This enables you to create a data context for the database and the class that contains the data field to customize. Para obter mais informações, consulte
Walkthrough: Creating a New Dynamic Data Web Site using Scaffolding.For more information, seeWalkthrough: Creating a New Dynamic Data Web Site using Scaffolding.
Comentários
Ao aplicar esse atributo a um campo de dados, você deve seguir as diretrizes para o uso dos atributos.When you apply this attribute to a data field, you must follow the guidelines for the use of the attributes. Para obter mais informações, consulte ASP.NET dados dinâmicos diretrizes.For more information, see ASP.NET Dynamic Data Guidelines.
Construtores
| DisplayFormatAttribute() |
Inicializa uma nova instância da classe DisplayFormatAttribute.Initializes a new instance of the DisplayFormatAttribute class. |
Propriedades
| ApplyFormatInEditMode |
Obtém ou define um valor que indica se a cadeia de caracteres de formatação especificada pela propriedade DataFormatString é aplicada ao valor do campo quando o campo de dados está no modo de edição.Gets or sets a value that indicates whether the formatting string that is specified by the DataFormatString property is applied to the field value when the data field is in edit mode. |
| ConvertEmptyStringToNull |
Obtém ou define um valor que indica se os valores de cadeia de caracteres vazia ("") são convertidos automaticamente em |
| DataFormatString |
Obtém ou define o formato de exibição do valor do campo.Gets or sets the display format for the field value. |
| HtmlEncode |
Obtém ou define um valor que indica se o campo deve ser codificado em HTML.Gets or sets a value that indicates whether the field should be HTML-encoded. |
| NullDisplayText |
Obtém ou define o texto exibido em um campo quando o valor do campo é |
| NullDisplayTextResourceType |
Obtém ou define o Type que contém os recursos para NullDisplayText.Gets or sets the Type that contains the resources for NullDisplayText. Usando o NullDisplayTextResourceType junto com NullDisplayText, permite que o método GetNullDisplayText() retorne valores localizados.Using NullDisplayTextResourceType along with NullDisplayText, allows the GetNullDisplayText() method to return localized values. |
| TypeId |
Quando implementado em uma classe derivada, obtém um identificador exclusivo para este Attribute.When implemented in a derived class, gets a unique identifier for this Attribute. (Herdado de Attribute) |
Métodos
| Equals(Object) |
Retorna um valor que indica se essa instância é igual a um objeto especificado.Returns a value that indicates whether this instance is equal to a specified object. (Herdado de Attribute) |
| GetHashCode() |
Retorna o código hash para a instância.Returns the hash code for this instance. (Herdado de Attribute) |
| GetNullDisplayText() |
Retorna a cadeia de caracteres de exibição da interface do usuário para NullDisplayText.Returns the UI display string for NullDisplayText. |
| GetType() |
Obtém o Type da instância atual.Gets the Type of the current instance. (Herdado de Object) |
| IsDefaultAttribute() |
Quando substituído em uma classe derivada, indica se o valor dessa instância é o valor padrão para a classe derivada.When overridden in a derived class, indicates whether the value of this instance is the default value for the derived class. (Herdado de Attribute) |
| Match(Object) |
Quando substituído em uma classe derivada, retorna um valor que indica se essa instância é igual a um objeto especificado.When overridden in a derived class, returns a value that indicates whether this instance equals a specified object. (Herdado de Attribute) |
| MemberwiseClone() |
Cria uma cópia superficial do Object atual.Creates a shallow copy of the current Object. (Herdado de Object) |
| ToString() |
Retorna uma cadeia de caracteres que representa o objeto atual.Returns a string that represents the current object. (Herdado de Object) |
Implantações explícitas de interface
| _Attribute.GetIDsOfNames(Guid, IntPtr, UInt32, UInt32, IntPtr) |
Mapeia um conjunto de nomes para um conjunto correspondente de identificadores de expedição.Maps a set of names to a corresponding set of dispatch identifiers. (Herdado de Attribute) |
| _Attribute.GetTypeInfo(UInt32, UInt32, IntPtr) |
Recupera as informações de tipo para um objeto, que pode ser usado para obter as informações de tipo para uma interface.Retrieves the type information for an object, which can be used to get the type information for an interface. (Herdado de Attribute) |
| _Attribute.GetTypeInfoCount(UInt32) |
Retorna o número de interfaces de informações do tipo que um objeto fornece (0 ou 1).Retrieves the number of type information interfaces that an object provides (either 0 or 1). (Herdado de Attribute) |
| _Attribute.Invoke(UInt32, Guid, UInt32, Int16, IntPtr, IntPtr, IntPtr, IntPtr) |
Fornece acesso a propriedades e métodos expostos por um objeto.Provides access to properties and methods exposed by an object. (Herdado de Attribute) |