Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bind query parameters to a model in ASP.NET Core

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?

like image 860
Carl Thomas Avatar asked Mar 21 '17 14:03

Carl Thomas


People also ask

How does model binding work in ASP.NET Core application?

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.

What are model binders in ASP.NET MVC?

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.

Is a process in which we bind a model to controller and view?

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.


2 Answers

You need to add [FromQuery] attribute to the model properties individually

public class Criteria {   [FromQuery(Name = "first_name")]   public string FirstName { get; set; } } 
like image 101
Carl Thomas Avatar answered Oct 08 '22 20:10

Carl Thomas


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)  {   } 
like image 42
peyman gilmour Avatar answered Oct 08 '22 18:10

peyman gilmour