I was under the impression that model binding in the ASP.Net Web API was supposed to support binding with the same minimum level of functionality supported by MVC.
Take the following controller:
public class WordsController : ApiController { private string[] _words = new [] { "apple", "ball", "cat", "dog" }; public IEnumerable<string> Get(SearchModel searchSearchModel) { return _words .Where(w => w.Contains(searchSearchModel.Search)) .Take(searchSearchModel.Max); } } public class SearchModel { public string Search { get; set; } public int Max { get; set; } }
I'm requesting it with:
http://localhost:62855/api/words?search=a&max=2
Unfortunately the model does not bind as it would in MVC. Why is this not binding as I would expect? I'm going to have a lot of different model types in my application. It would be nice if binding just worked, like it does in MVC.
[FromQuery] - Gets values from the query string. [FromRoute] - Gets values from route data. [FromForm] - Gets values from posted form fields. [FromBody] - Gets values from the request body.
Model Binding is the most powerful mechanism in Web API 2. It enables the response to receive data as per requester choice. i.e. it may be from the URL either form of Query String or Route data OR even from Request Body. It's just the requester has to decorate the action method with [FromUri] and [FromBody] as desired.
When Web API calls a method on a controller, it must set values for the parameters, a process called binding. By default, Web API uses the following rules to bind parameters: If the parameter is a "simple" type, Web API tries to get the value from the URI.
Take a look at this: How WebAPI does Parameter Binding
You need to decorate your complex parameter like so:
public IEnumerable<string> Get([FromUri] SearchModel searchSearchModel)
OR
public IEnumerable<string> Get([ModelBinder] SearchModel searchSearchModel)
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