ASP.NET Core MVC Interview Question #38

How does validation work in ASP.NET Core MVC?

Controllers, Actions, Model Binding & Action Results Junior Beginner

Quick Interview Answer

After model binding, MVC validates the bound model using configured validation mechanisms. Data annotation attributes such as Required, StringLength, Range, and Compare are commonly used on input models.

Detailed Explanation

After model binding, MVC validates the bound model using configured validation mechanisms. Data annotation attributes such as Required, StringLength, Range, and Compare are commonly used on input models.

Validation errors are added to ModelState. Server-side validation must remain authoritative even when client-side validation is enabled because client-side checks can be bypassed.

Code Example

public class RegisterViewModel
{
    [Required]
    [StringLength(100)]
    public string Name { get; set; } = string.Empty;

    [Range(18, 120)]
    public int Age { get; set; }
}