LearnAI ToolsCareerPractice BuildsPlayDevelopmentContact
Lesson 5418 min read

Model Binding & Validation

Learn how ASP.NET Core automatically binds request data to C# objects, and how to validate it with data annotations.

On this page 6 sections

What is Model Binding?

Model binding automatically maps incoming request data (route values, query strings, form fields, or JSON body) into strongly typed C# parameters and objects — you rarely need to parse raw request data by hand.

Binding Sources

AttributeSource
[FromRoute]URL route segments
[FromQuery]Query string (?key=value)
[FromBody]The JSON request body
[FromForm]Submitted form data
[HttpPost]
public IActionResult Create([FromBody] TaskDto dto)
{
// dto is automatically populated from the JSON body
return Ok(dto);
}

Validation with Data Annotations

Data annotation attributes describe validation rules directly on your model, and ASP.NET Core checks them automatically during model binding.

public class TaskDto
{
[Required]
[StringLength(100, MinimumLength = 3)]
public string Title { get; set; } = "";
[Range(1, 5)]
public int Priority { get; set; }
}

Checking ModelState

[HttpPost]
public IActionResult Create([FromBody] TaskDto dto)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
return Ok("Task created!");
}
[ApiController] Simplifies This

Controllers marked with [ApiController] automatically return a 400 Bad Request with validation errors if the model is invalid — you often don't need to check ModelState.IsValid manually in a Web API.

FAQs

Yes — implement IValidatableObject on your model, or create a custom ValidationAttribute for reusable rules.

Summary

  • Model binding automatically populates C# objects from request data.
  • Data annotations (Required, StringLength, Range) declare validation rules on the model.
  • [ApiController] automatically handles invalid models with a 400 response.
Next Lesson →

Layouts & Partial Views