Easy way to Model Binding in ASP.NET Core
Great way to model binding in API, .NET MVC, and Razor Pages
When an HTTP request hits the server, it carries data. That data lives in various places within the request, such as the URL Route, Query string, Request Header, or the body of the request.
Sometimes programmers get data from a form using this way programmer had to write a considerable amount of code to pick out all the data from the request and need to convert in various data types
[HttpPost]
public async Task<IActionResult> Create()
{
Product product = new Product();
product.Name = Request.Form["Name"];
//still need to parse out 20 more fields.
}
Writing this type of code is tedious, repetitive, and ripe for being abstracted away. Enter model binding.
Model Binding
Today we will discuss a few in-built model binders which can save lots of time and improve reusability.
- [FromQuery] - Gets values from the query string.
- [FromRoute] - Gets values from route data.
- [FromForm] - Gets values from posted form fields. (Content type: application/x-www-url-formencoded)
- [FromBody] - Gets values from the request body. (Content type: application/json)
- [FromHeader] - Gets values from HTTP headers.
FromQuery
It helps to get values from the query string.
Here I am adding two examples.
API Action
[HttpGet]
public async Task<IActionResult> Validate([FromQuery(Name = "vatId")]int taxId)
{
//code
}
FromRoute
Essentially it FromRoute will look at your route parameters and extract/bind the data based on that. As the route, when called externally, is usually based on the URL. In the previous version(s) of web API, this is comparable to FromUri.
[HttpPut("{id}")]
public async Task<IActionResult> Edit([FromRoute]int id)
{
//code
}
FromForm
The FromForm attribute is for incoming data from a submitted form sent by the content-type application/x-www-url-formencoded
[HttpPut("{id}")]
public async Task<IActionResult> Edit([FromForm]Product product)
{
//code
}
FromBody
The FromBody attribute is for incoming data from a submitted form sent by the content-type application/json
[HttpPut("{id}")]
public async Task<IActionResult> Edit([FromBody]Product product)
{
//code
}
FromHeader
via FromHeader attribute we can get data from the HTTP Request Header
[HttpPut("{id}")]
public async Task<IActionResult> Edit([FromHeader(Name = "User-Agent")]string userAgent)
{
//code
}
Create your own binding based on your requirements
Refer below link