Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.Net Web API model binding not working like it does in MVC 3

Tags:

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.

like image 539
Nathan Ridley Avatar asked Jun 02 '12 15:06

Nathan Ridley


People also ask

What is difference between FromQuery and FromBody?

[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.

Which of the following are relevant to model binding in Web API?

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.

How do we do parameter binding in Web API?

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.


1 Answers

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) 
like image 179
Michael Baird Avatar answered Sep 28 '22 23:09

Michael Baird