Isaac.

Understanding ASP.NET Model Binding (with Examples)

When building web applications with ASP.NET Core, one of the features that makes developers’ lives easier is model binding. It automatically maps incoming HTTP request data (like form fields, query strings, route values, and JSON bodies) to your C# objects. This means you don’t need to manually parse request data—ASP.NET does it for you.

What is Model Binding?

Model binding is the process of taking HTTP request data and converting it into .NET objects that your controller or Razor Page methods can use directly.

Basic Example: Binding Simple Types

public IActionResult GetProduct(int id)
{
    return Content($"You asked for product with ID = {id}");
}

If you call /Products/GetProduct?id=10, ASP.NET automatically binds id=10 from the query string to the id parameter.

Binding Complex Types

public class User
{
    public string Name { get; set; }
    public int Age { get; set; }
    public string Email { get; set; }
}

[HttpPost]
public IActionResult CreateUser(User user)
{
    return Content($"User {user.Name}, Age {user.Age}, Email {user.Email} created!");
}

If a form submits these values:

<form method="post" action="/Home/CreateUser">
    <input name="Name" />
    <input name="Age" />
    <input name="Email" />
    <button type="submit">Submit</button>
</form>

ASP.NET will bind the form fields into the User object automatically.

Binding from Route Values

[Route("products/{id}")]
public IActionResult Details(int id)
{
    return Content($"Product details for ID = {id}");
}

If a user goes to /products/25, the route value 25 is automatically bound to the id parameter.

Binding from JSON (Web APIs)

[HttpPost]
[Route("api/users")]
public IActionResult CreateUser([FromBody] User user)
{
    return Ok(new { message = $"User {user.Name} created!" });
}

Request (JSON):

{
  "name": "Alice",
  "age": 30,
  "email": "alice@example.com"
}

The JSON body is deserialized and bound to the User object.

Binding Collections

public IActionResult SubmitIds(int[] ids)
{
    return Content($"You submitted {string.Join(", ", ids)}");
}

If a query string like /submitids?ids=1&ids=2&ids=3 is sent, it will bind into int[] ids = {1, 2, 3}.

Summary

In short, model binding lets you focus on business logic instead of request plumbing.