Introduction
In this article, we will cover ASP.NET Core Model Binding.
So, Let's get started.
ASP.NET Core Model Binding
Model binding in ASP.NET Core is a mechanism that maps client request data (like form values, route data, query string parameters, request body, and HTTP headers) to action method parameters. This allows us to work directly with strongly typed .NET objects in our action methods. This will eliminate the need to manually parse and convert the raw HTTP request data to .NET objects in the ASP.NET Core MVC Application.
[HttpGet("{id}")]
public ActionResult GetEmployeeById(int id)
{
// Your code for retrieving an employee by ID goes here
// ...
}
Why Is Model Binding Important in ASP.NET Core?
- Type Safety: Model binding converts client data into .NET types, ensuring that our action methods values are already of the expected data type. This will reduce the need for manual data type conversions and associated error checks.
- Automatic Validation: Model binding can validate the incoming data against predefined rules when combined with data annotations. We can easily check if the data is valid by examining the ModelState.IsValid property. How to use ModelState.IsValid property will be discussed in detail in our upcoming articles.
- Code Simplification: Model binding eliminates the repetitive code of manually extracting values from the request and converting them to .NET types.
How Model Binding Works in ASP.NET Core?
- Parameter Names and Source: The model binder looks for data in the request that matches the names of the action method’s parameters. Depending on the source attribute (e.g., [FromQuery], [FromBody], [FromRoute]), it knows where to look, such as in the query string, the request body, or the route data.
- Type Conversion: The model binder converts the data to the parameter’s type once a match is found. For instance, a string from the query string can be converted to an integer if the action method expects an integer parameter.
- Data Validation: If the model is decorated with validation attributes (like [Required], [Range], [MaxLength], [MinLength] Data Annotation Attributes), the model binder will also validate the data after binding it. The results of the validation are stored in the ModelState.
Model Binding Techniques in ASP.NET Core
- Basic Model Binding: ASP.NET Core MVC tries to bind request data to the action method parameters by name.
public IActionResult Register(string username, string password)
{
// Your registration logic goes here
// ...
}
The HTTP request has a form or query string with a username and password; those will be automatically bound to the method parameters.
- Attribute Routing: Model binding can bind data from the URL using attribute routing.
[Route("employee/{id}")]
public IActionResult EmployeeDetails(int id)
{
//...
}
- FromBody ([FromBody]): Gets values from the request body.
Binding data from the request body of an HTTP request. This attribute is particularly useful when you need to receive complex data, such as JSON or XML, from the client in the body of a POST or PUT request.
[HttpPost]
public IActionResult CreateEmployee([FromBody] Employee employee)
{
// Your code for creating an employee goes here
// ...
}
- FormForm ([FromForm]): Gets values from posted form fields.
Binding data from HTML form submissions or multipart/form-data requests. This attribute allows you to map data sent by the client through form-to-action method parameters. It's particularly useful when you need to handle data submitted in HTML form on web pages.
- FromHeader ([FromHeader]): Gets values from HTTP headers. Binding data from HTTP headers in an HTTP request. This attribute allows you to access and use data present in the headers of the incoming request. It is commonly used to extract specific information such as authentication, custom headers, content negotiation, and other header-related operations.
public IActionResult CheckUserAgent([FromHeader(Name = "User-Agent")] string userAgent)
{
// Your code for checking the User-Agent header goes here
// ...
}
- FormRoute ([FormRoute]): Gets values from route data. Extracting values from the URL's path and using them within your endpoints. It enables resource identification, clean URLs, API versioning, and handling complex route structures.
[HttpGet("{id}")]
public IActionResult Get(int id)
{
// Your code for handling the GET request with an 'id' parameter goes here
// ...
}
- FormQuery ([FormQuery]): Gets values from the query string. Extracting and working with data provided in the query string of a URL. It enables scenarios such as filtering, searching, pagination, sorting, and more.
public IActionResult Search([FromQuery] string query)
{
// Your code for performing a search with the 'query' parameter goes here
// ...
}
- Complex Type Binding: ASP.NET Core MVC can bind complex types by recursively binding properties of the complex type. For instance, if you submit a form with the fields Employee.Name and Employee. Department, they can be bound to a complex object.
public IActionResult Create(Employee employee)
{
// Your code for creating an employee record goes here
// ...
}
Important Points to Remember
- Naming the form fields, query string parameters, or route values is crucial. They should match the names of the action method’s parameters for model binding to work correctly.
- Always validate the data after model binding using the ModelState.IsValid property. This ensures that the data conforms to the expected format and rules.
- Be wary of over-posting. Do not blindly bind client data directly to your database models, as this can expose your application to vulnerabilities. Use ViewModels or DTOs (Data Transfer Objects) to protect against this.
Summary
In this article, I have tried to cover some of the ASP.NET Core Model Binding.