Data Annotations in ASP.NET
Data annotations are frequently used to regulate how model classes behave in relation to views, databases, and validation procedures.
This Article helps to understand the concept of Data Annotations in ASP.NET
Our model properties can have Attributes (classes) applied to them called Data Annotations, which tell them how to behave in different scenarios.
Validation Attributes /Data Annotations:
[Required]: Mark property as a required field.
[StringLength(maxLength, MinimumLength = minLength)]: Specify the maximum and optional minimum length of for a string field.
[Required(ErrorMessage = "Last Name is Required.")]
[Range(min, max)]: Specifies the minimum and maximum value for a Numeric property.
[EmailAddress]: Validates that the property has an a valid email address.
[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)]: Validates that the property has an a valid date.
[DisplayFormat(DataFormatString = “{0:yyyy-MM-dd}”, ApplyFormatInEditMode = true)]: Impose a custom formatting for a property.
Display Attributes:
[Display(Name = “Display Name”)]: Specifies the display name for a property.
[HiddenInput(DisplayValue = false)]: Mark a property as a hidden input element.
[DisplayOrder(order)]: Used to specify the order in which fields are displayed.
Database-Related Attributes (Work only With Entity Framework Core):
[Key]: Indicates that a property is a primary key.
[ForeignKey(“RelatedEntity”)]: Indicates that a property is a foreign key.
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]: Specifies how the database generates values for a primary key.
[Column(“ColumnNameInDb”)]: Specifies a different column name in the database than the property name in the model.
Misc Attributes:
[ReadOnly(true)]: Mark a property as read-only and non-editable.
Data Annotations in ASP.NET Core MVC Indicates that scaffolding mechanisms should ignore a property.
What's Your Reaction?