Model Binding & Validation
1. What Is Model Binding?
Model binding automatically maps data from an HTTP request into:
- Action method parameters
- Model objects (classes)
Sources include:
- Route values
- Query strings
- Form data
- Request body (JSON / XML)
- Headers
Mental model: HTTP request → strongly typed C# objects
2. When Model Binding Happens
- Routing selects the action
- Model binding populates parameters
- Validation runs
- Action method executes
3. Binding Order (Important)
ASP.NET Core checks sources in this order:
- Form data (POST)
- Route data
- Query string
Unless you override it with attributes.
4. Common Binding Attributes (Know These)
| Attribute | Binds From |
|---|---|
[FromRoute] | URL segments |
[FromQuery] | Query string |
[FromBody] | Request body (JSON/XML) |
[FromHeader] | HTTP headers |
public IActionResult Get(
[FromRoute] int id,
[FromQuery] int page,
[FromHeader(Name="User-Agent")] string agent)
Use attributes for clarity & safety.
5. Route Data vs Query String
Route Data
- Clean, REST-style URLs
- Required or optional
/products/{id}
Query String
- Filtering, sorting, paging
/products?page=2&sort=price
Rule of thumb:
- Identity → route
- Options → query
6. Binding to Model Classes (Very Common)
public IActionResult Create(Book book)
ASP.NET Core:
- Matches request data to property names
- Converts types automatically
- Fills the model
{
"bookId": 1,
"author": "Harsha"
}
No manual parsing needed.
7. [FromBody] (APIs)
Used for JSON/XML payloads.
public IActionResult Register([FromBody] Person person)
Key rules:
- Uses input formatters
- Based on
Content-Type - Only one
[FromBody]per action
8. Input Formatters (High Level)
They deserialize request bodies:
- JSON →
System.Text.Json - XML →
XmlSerializer
Configured in Program.cs:
builder.Services.AddControllers().AddXmlSerializerFormatters();
You rarely touch them unless adding formats.
9. Model Validation (Runs Automatically)
After binding, ASP.NET Core validates using:
- Data annotations
- Custom validation
- IValidatableObject
if (!ModelState.IsValid) {
return BadRequest(ModelState);
}
10. Common Data Annotations
| Attribute | Purpose |
|---|---|
[Required] | Must have value |
[StringLength] | Length limit |
[Range] | Numeric range |
[EmailAddress] | Email format |
[Compare] | Match another field |
11. IValidatableObject (Model-Level Rules)
Used when validation depends on multiple properties.
public IEnumerable<ValidationResult> Validate(...)
{
if (StartDate > EndDate)
yield return new ValidationResult("Invalid date range");
}
Property annotations = single field
IValidatableObject= cross-field rules
12. Prevent Overposting ([Bind], [BindNever])
[Bind]
Allow only specific fields
public IActionResult Create([Bind("Title,Author")] Book book)
[BindNever]
Never bind this property
[BindNever]
public DateTime CreatedAt { get; set; }
Security best practice.
13. Collections Binding
Works automatically:
{
"tags": ["music", "coding"]
}
public List<string> Tags { get; set; }
No extra config needed.
14. Custom Model Binders (Advanced)
Used only when defaults aren't enough:
- Weird formats
- Custom parsing rules
Steps:
- Implement
IModelBinder - Register via
ModelBinderProvider
Rare in day-to-day work.
15. Interview One-Liner 🎯
"Model binding in ASP.NET Core maps request data from routes, queries, headers, and bodies into strongly typed parameters and models. Validation runs automatically using data annotations or custom rules, and ModelState tracks errors."