Model Binding & Validation
Master model binding, validation, and data annotation in ASP.NET Core. This is a foundational concept in cross-platform .NET development that professional developers rely on daily. The explanations below are written to be beginner-friendly while covering the depth and nuance that comes from real-world .NET Core experience. Take your time with each section and practice the examples
65 min•By Priygop Team•Last updated: Feb 2026
Model Binding
Example
// From query string
public IActionResult GetUsers([FromQuery] int page, [FromQuery] int size)
{
// page and size are bound from query parameters
}
// From route
[HttpGet("{id}")]
public IActionResult GetUser([FromRoute] int id)
{
// id is bound from route parameter
}
// From body
[HttpPost]
public IActionResult CreateUser([FromBody] CreateUserRequest request)
{
// request is bound from JSON body
}
// From form
[HttpPost]
public IActionResult UploadFile([FromForm] IFormFile file)
{
// file is bound from form data
}Data Validation
Example
public class CreateUserRequest
{
[Required(ErrorMessage = "Name is required")]
[StringLength(100, MinimumLength = 2)]
public string Name { get; set; }
[Required]
[EmailAddress]
public string Email { get; set; }
[Range(18, 120, ErrorMessage = "Age must be between 18 and 120")]
public int Age { get; set; }
[Phone]
public string? PhoneNumber { get; set; }
[RegularExpression(@"^[A-Z]{2}d{6}$", ErrorMessage = "Invalid ID format")]
public string? NationalId { get; set; }
}
// Custom validation attribute
public class ValidAgeAttribute : ValidationAttribute
{
public override bool IsValid(object value)
{
if (value is int age)
{
return age >= 18 && age <= 120;
}
return false;
}
}Try It Yourself — ASP.NET Core Web Development
Try It Yourself — ASP.NET Core Web DevelopmentHTML
HTML Editor
✓ ValidTab = 2 spaces
HTML|32 lines|1593 chars|✓ Valid syntax
UTF-8