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?
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:
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