I am trying to use model binding from query parameters to an object for searching.
My search object is
[DataContract] public class Criteria { [DataMember(Name = "first_name")] public string FirstName { get; set; } }
My controller has the following action
[Route("users")] public class UserController : Controller { [HttpGet("search")] public IActionResult Search([FromQuery] Criteria criteria) { ... } }
When I call the endpoint as follows .../users/search?first_name=dave
the criteria property on the controller action is null. However, I can call the endpoint not as snake case .../users/search?firstName=dave
and the criteria property contains the property value. In this case Model Binding has worked but not when I use snake_case.
How can I use snake_case with Model Binding?
Model binding allows controller actions to work directly with model types (passed in as method arguments), rather than HTTP requests. Mapping between incoming request data and application models is handled by model binders.
Model binding is a well-designed bridge between the HTTP request and the C# action methods. It makes it easy for developers to work with data on forms (views), because POST and GET is automatically transferred into a data model you specify. ASP.NET MVC uses default binders to complete this behind the scene.
Model binding is a process in which we bind a model to controller and view. It is a simple way to map posted form values to a . NET Framework type and pass the type to an action method as a parameter. It acts as a converter because it can convert HTTP requests into objects that are passed to an action method.
You need to add [FromQuery]
attribute to the model properties individually
public class Criteria { [FromQuery(Name = "first_name")] public string FirstName { get; set; } }
Solution for .net core 2.1, 2.2, 3.0 and 3.1
Or without attributes you can do something like this which is cleaner I think (of course if the model properties are same as query parameters).
Meanwhile I use it in .net core 2.1, 2.2 and 3.0 preview & 3.1.
public async Task<IActionResult> Get([FromQuery]ReportQueryModel queryModel) { }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With