Previous Synchronous and Asynchronous in .NET Core Securing ASP.NET Core Web API Next

Model Binding & Validation in ASP.NET Core

🧩 1. Model Binding — What It Is

Definition: Model Binding is the ASP.NET Core feature that automatically maps incoming HTTP request data (form fields, query strings, route values, headers, JSON body, etc.) to action method parameters or model object properties.

Instead of manually parsing Request.Form, Request.Query, or Request.Body, ASP.NET Core does the mapping for you.

Sources of data for model binding:

  • Form fields (<input> values in POST forms)
  • Route data (/products/details/5 → id = 5)
  • Query strings (?page=2&sort=asc)
  • Headers
  • JSON body (common in APIs)

Example:

public class Student
{
    public int Id { get; set; }
    public string Name { get; set; }
    public int Age { get; set; }
}

public class StudentController : Controller
{
    [HttpPost]
    public IActionResult Save(Student student)
    {
        // Model binding maps request data to 'student'
        return View(student);
    }
}
    

If the form posts Id=1&Name=John&Age=20, ASP.NET Core automatically fills the student object.

✅ 2. Model Validation — What It Is

Definition: After model binding, ASP.NET Core validates the bound model against rules you define (usually via Data Annotations or custom validation logic).

Validation ensures that the data meets business rules before your action method processes it.

Common validation attributes:

  • [Required] — field must have a value
  • [StringLength(max)] — limit string length
  • [Range(min, max)] — numeric range
  • [EmailAddress], [Phone], [Url] — format checks
  • [RegularExpression(pattern)] — custom regex

Example:

public class Student
{
    public int Id { get; set; }

    [Required(ErrorMessage = "Name is required")]
    [StringLength(50, ErrorMessage = "Name cannot exceed 50 characters")]
    public string Name { get; set; }

    [Range(18, 60, ErrorMessage = "Age must be between 18 and 60")]
    public int Age { get; set; }
}
    

🔄 3. How They Work Together

Flow:

  1. Model Binding maps request data → model object.
  2. Model Validation checks the model against rules.
  3. If validation fails:
    • In MVC: ModelState.IsValid will be false.
    • In Web API with [ApiController]: ASP.NET Core automatically returns HTTP 400 with validation errors.

MVC Example:

[HttpPost]
public IActionResult Save(Student student)
{
    if (!ModelState.IsValid)
    {
        // Return same view with validation errors
        return View(student);
    }

    // Save to DB
    return RedirectToAction("Success");
}
    

Web API Example with [ApiController]:

[ApiController]
[Route("api/[controller]")]
public class StudentsController : ControllerBase
{
    [HttpPost]
    public IActionResult Create(Student student)
    {
        // No need to check ModelState.IsValid manually
        // Invalid models return 400 automatically
        return Ok(student);
    }
}
    

🛠 4. Best Practices

  • Use [ApiController] for APIs to get automatic 400 responses.
  • Keep validation rules in the model (Data Annotations) for consistency.
  • Use IValidatableObject or custom attributes for complex rules.
  • Avoid manual parsing of request data unless necessary — let model binding handle it.
  • Always check ModelState.IsValid in MVC before processing.
  • For computed properties, you can re-run validation with:
    ModelState.ClearValidationState(nameof(Model));
    TryValidateModel(Model, nameof(Model));
                

ASP.NET Core Request → Model Binding → Model Validation Flow

HTTP Request Arrives

Could be GET, POST, PUT, etc.

Data sources: Route values, query string, form fields, headers, JSON body.

Model Binding

ASP.NET Core inspects the request and matches incoming data to action parameters or model properties.

Sources are checked in a specific order: route → query → form → body → others.

If binding fails for a property, ModelState gets an error.

Model Validation

Runs immediately after binding.

Uses Data Annotations ([Required], [Range], etc.), IValidatableObject, or custom validators.

Validation results are stored in ModelState.

Decision Point: Is Model Valid?

  • Yes: Action executes with the bound model.
  • No:
    • In MVC: You check ModelState.IsValid and return the view with errors.
    • In API with [ApiController]: Framework auto-returns 400 Bad Request with validation error details.

Action Execution

Your business logic runs using the validated model.

Response is sent back to the client.

📌 Summary Table

Feature Purpose Triggered When Common Use
Model Binding Maps HTTP request data to parameters/models Before action executes Populate objects from form/query/JSON
Model Validation Ensures data meets rules After model binding Enforce business/data constraints
Back to Index
Previous Synchronous and Asynchronous in .NET Core Securing ASP.NET Core Web API Next
*