CuriousDeveloper
CuriousDeveloper

Reputation: 899

AJAX post string array to webapi 2

Here is my ajax call:

var myIds = ["A","B","C"]
$.ajax({
    type: "POST",
    url: /DoStuffAndThings?year=2018&name=test,
    data: {myIds: myIds},
    traditional: false
});

Here is my controller action:

[HttpPost]
public void DoStuffAndThings(int year, string name, [FromBody] List<string> myIds) {
    // do stuff
}

year and name come through without issue but myIds is always empty.

Ive tried

data: {myIds: myIds} and data: myIds and data: {"": myIds} and I tried using Ienumerable<string> and List<string> and string[]

and I've tried traditional: true and false

Upvotes: 1

Views: 511

Answers (2)

Nkosi
Nkosi

Reputation: 247068

The model binder is unable to parse the send data as it does not know the format

Use JSON.stringify along with the corresponding parameters

var myIds = ["A","B","C"];
$.ajax({
    type: "POST",
    url: "/DoStuffAndThings?year=2018&name=test",
    contentType: "application/json",
    dataType: "json",
    data:JSON.stringify(myIds),
    traditional: false
});

The model binder should then be able to recognize the string collection in the body of the request.

Upvotes: 1

Rodrigo Rocha
Rodrigo Rocha

Reputation: 1

When sending data to a web server, the data has to be a string. Convert a JavaScript object into a string with JSON.stringify().

Before data, use JSON.stringify(myIds).

 var myIds = ["A","B","C"]
  $.ajax({
       type: "POST",
       contentType: "application/json",
       dataType: 'json',
       url: /DoStuffAndThings?year=2018&name=test,
       data: JSON.stringify(myIds),
       traditional: false
 });

Upvotes: 0

Related Questions