Reputation: 6362
Data Model
public class Foo
{
public string Id { get; set; }
public string Title { get; set; }
}
Web API 2 Controller
[Route("api/UpdateFoo")]
public IHttpActionResult UpdateFoo(List<Foo> Foos)
{
}
JS
// here I need to create fooData which is list of foo
var fooData = [];
fooData.push({ Title: "title1" });
fooData.push({ Title: "title2" });
$.ajax({
method: "POST",
url: "api/UpdateFoo",
data: fooData
}).done(function (result) {
// good
}).fail(function(xhr) {
alert(xhr.responseText);
});
What am I missing here? in fiddler it looks like I've sending fooData right however it is not recieved in Web Api Controller, I am being able to enter the the method with breakpoint however the value in an empty list
Upvotes: 0
Views: 1092
Reputation: 21
I just spent a couple of hours yesterday on this. There is a known "quirk" in asp.net webApi when posting data via ajax See Quirk Here. And to summarize in your particular issue just add the following:
var fooData = [];
fooData.push({ Title: "title1" });
fooData.push({ Title: "title2" });
$.ajax({
method: "POST",
url: "api/UpdateFoo",
data: {'': fooData} //<-- the '' empty prefix name for the data
}).done(function (result) {
// good
}).fail(function(xhr) {
alert(xhr.responseText);
});
Upvotes: 2
Reputation: 4978
Try making your Ajax call:
$.ajax({
method: "POST",
url: "api/UpdateFoo",
data: JSON.stringify(fooData),
contentType: 'application/json'
}).done(function (result) {
// good
}).fail(function(xhr) {
alert(xhr.responseText);
});
Upvotes: 0
Reputation: 3145
Create another model to contain List
public class ListOfFoos
{
public List<Foo> Foos {get; set;}
public ListOfFoos()
{
Foos = new List<Foo>();
}
}
then your controller should look like this:
[Route("api/UpdateFoo")]
public IHttpActionResult UpdateFoo(ListOfFoos listOfFoos)
{
}
now if you pass in JSON like this, you should be able to get the list in controller:
{
"foos" : [
{ "Id": 1, "Title" : "f1" },
{ "Id": 2, "Title" : "f2" }
]
}
Upvotes: 1