DEV Community

Sardar Mudassar Ali Khan
Sardar Mudassar Ali Khan

Posted on

Using datatype and displaycolumn attributes in asp net mvc application

In an ASP.NET MVC application, you can use the DataType and DisplayColumn attributes to provide additional metadata for model properties, which can be used for validation and display purposes.

The DataType attribute allows you to specify the data type of a property. This can be useful for validating user input or formatting data when displaying it. Here's an example:

public class Person
{
    [DataType(DataType.Date)]
    public DateTime BirthDate { get; set; }

    [DataType(DataType.EmailAddress)]
    public string Email { get; set; }
}
Enter fullscreen mode Exit fullscreen mode

In this example, the BirthDate property is annotated with the DataType attribute and set to DataType.Date, indicating that the property represents a date value. Similarly, the Email property is annotated with the DataType attribute and set to DataType.EmailAddress, indicating that the property represents an email address.

The DisplayColumn attribute allows you to specify a column to use for display purposes when scaffolding views. It can be applied to a class to specify a default display column or to individual properties to override the default. Here's an example:

[DisplayColumn("FullName")]
public class Person
{
    public string FirstName { get; set; }

    public string LastName { get; set; }

    [Display(Name = "Full Name")]
    public string FullName => $"{FirstName} {LastName}";
}
Enter fullscreen mode Exit fullscreen mode

In this example, the DisplayColumn attribute is applied to the Person class, specifying that the FullName property should be used as the default display column. The FullName property is also annotated with the Display attribute, which sets the display name to "Full Name". This way, when scaffolding views, the FullName property will be used as the default display column, and its display name will be "Full Name".

These attributes can be helpful when working with form validation, generating views using scaffolding, or displaying data in a user-friendly format.

Top comments (0)