Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery $.ajax call to Web Api with string arrays

I am trying to call a .net Web Api method via jquery's $.ajax. When I pass in

var process = "first process", var nameArray = ["first", "second"], var valueArray = ["val1", "val2"]

and then:

 $.ajax({
url: jsonFeed,
data: {process: process, nameArray: nameArray, valueArray: valueArray},
    etc...

I have a ASP.NET Web Api method:

  public string GetResponseToken(string process, string[] nameArray, string[] valueArray)

When I run everything, I receive an error message:

"Can't bind multiple parameters ('nameArray' and 'valueArray') to the request's content."

Does anyone know why this is, or how I can fix it to accept my arrays?

like image 789
Logan W Avatar asked Oct 17 '12 18:10

Logan W


1 Answers

The Web.API parameter/model binder work differently than the MVC one. You need to tell it that you wan't to bind all of your arguments from the query string with the [FromUri] attribute:

public string GetResponseToken(
      [FromUri]string process, 
      [FromUri]string[] nameArray, 
      [FromUri]string[] valueArray)
{
    //... 
}

In the long run (e.g the above mentioned approach won't work if you your request type is a POST) you should consider to use a parameter object instead of having multiple arguments.

public string GetResponseToken([FromUri]ResponseTokenRequest request)
{
    //...
}

public class ResponseTokenRequest
{
    public string Process { get; set; }
    public string[] NameArray { get; set; }
    public string[] ValueArray { get; set; }
}

You can learn about the Wep.API parameter binding in the following articles:

  • How WebAPI does Parameter Binding
  • Passing multiple POST parameters to Web API Controller Methods
like image 144
nemesv Avatar answered Sep 18 '22 01:09

nemesv