Data Annotations in ASP.NET Core MVC

Data Annotations in ASP.NET Core MVC

In this article, I will briefly introduce Data Annotations in ASP.NET Core MVC Applications. Please read our previous article discussing Model Binding in ASP.NET Core MVC Applications.

Data Annotations in ASP.NET Core MVC

In ASP.NET Core MVC, data annotations are commonly used to control the behavior of model classes when they interact with views, databases, and validation processes. Data Annotations are Attributes (classes) that we can apply to our model properties to specify how they should be treated in various situations. These data annotations are primarily used in ASP.NET Core MVC and Razor Pages applications.

So, the first important point that you need to remember is Data Annotation in ASP.NET Core MVC are not only used for Validation Purpose but also are used when we are working with Entity Framework Core Model First Approach to create the database based on our model as well as when we want how the model properties should display in a Razor View. Let us try to see some of the commonly used data annotations and their descriptions:

Validation Attributes:
  • [Required]: Indicates that the property is a required field.
  • [StringLength(maxLength, MinimumLength = minLength)]: Specifies the maximum and optional minimum length of characters allowed for a string field.
  • [Range(min, max)]: Specifies the minimum and maximum value for a Numeric property.
  • [EmailAddress]: Validates that the property has an email format.
  • [RegularExpression(pattern)]: Validates a property against a regular expression.
  • [Compare(“OtherProperty”)]: Validates that the property value matches another property’s value.
Formatting Attributes:
  • [DataType(DataType.Date)]: Specifies that a property should be treated as a date.
  • [DisplayFormat(DataFormatString = “{0:yyyy-MM-dd}”, ApplyFormatInEditMode = true)]: Provides a custom formatting for a property.
Display Attributes:
  • [Display(Name = “Display Name”)]: Specifies the display name for a property.
  • [HiddenInput(DisplayValue = false)]: Indicates that a property should be rendered as a hidden input element.
  • [DisplayOrder(order)]: Used to specify the order in which fields are displayed.
Database-Related Attributes (Used With Entity Framework Core):
  • [Key]: Indicates that a property is a primary key.
  • [ForeignKey(“RelatedEntity”)]: Specifies that a property is a foreign key.
  • [DatabaseGenerated(DatabaseGeneratedOption.Identity)]: Specifies how the database generates values for a property.
  • [Column(“ColumnNameInDb”)]: Specifies a different column name in the database than the property name in the model.
Other Attributes:
  • [ReadOnly(true)]: Indicates that a property is read-only and its value cannot be modified.
  • [ScaffoldColumn(false)]: Indicates that scaffolding mechanisms should ignore a property.
How to Use Data Annotations in ASP.NET Core MVC?

Here’s an example of a model class with data annotations. We need to include System.ComponentModel.DataAnnotations namespace, which provides the Data Annotations Attributes.

using System.ComponentModel.DataAnnotations;
namespace DataAnnotationsDemo.Models
{
    public class User
    {
        [Key]
        public int Id { get; set; }

        [Required(ErrorMessage = "First Name is Required.")]
        [StringLength(50, ErrorMessage = "First Name Should not Exceed 50 Characters.")]
        [Display(Name = "First Name")]
        public string FirstName { get; set; }

        [Display(Name = "Last Name")]
        public string LastName { get; set; }

        [EmailAddress(ErrorMessage = "Invalid Email Address.")]
        public string Email { get; set; }

        [DataType(DataType.Password)]
        [StringLength(50, MinimumLength = 6, ErrorMessage = "Password Must Be Between 6 and 30 Characters.")]
        public string Password { get; set; }

        [DataType(DataType.Password)]
        [Compare("Password", ErrorMessage = "Passwords Do Not Match.")]
        [Display(Name = "Confirm Password")]
        public string ConfirmPassword { get; set; }
    }
}

In the next article, I will discuss Model Validations in ASP.NET Core MVC with Examples. In this article, I try to explain Data Annotations in ASP.NET Core MVC with Examples. I hope you enjoy the Data Annotations in ASP.NET Core MVC article.

Leave a Reply

Your email address will not be published. Required fields are marked *