Post an array of objects to WebAPI using jQuery


This is quite niche but caught me out the other day.

Let’s say you have a person entity:

public class Person
{
    public int Id { get; set; }
    public string Name { get; set; }
    public int Age { get; set; }
}

and you have a WebAPI method that takes in a group:

public class UsersController : ApiController
{
    public IEnumerable<Person>Post(IEnumerable<Person> persons)
    {
        // do some registration work
    }
}

You create your call in JavaScript something like this:

var people = [];
people.push({ name: 'Kev', age: 32 });
people.push({ name: 'Ian', age: 31 });
people.push({ name: 'Garry', age: 32 });
 
var request = $.ajax({
  dataType: 'json',
  url: '/api/users',
  method: 'POST',
  data: people,
});

You POST that to the API and you get… an empty array. Not great.

jQuery quirk

Turns out this is a known issue and the fix is pretty simple.

Change your data to be a single anonymous object instead of a raw array and it’ll work. So this:

var request = $.ajax({
  dataType: 'json',
  url: '/api/users',
  method: 'POST',
  data: { '': people },
});

Easy.