Ajax post to ASP.net MVC controller – object properties are null

Have I missed something?

Yes, take a look at the following article to understand the correct wire format that the default model binder expects for binding collections. In other words, for this to work, instead of:

items[0][Name]       | Name 1
items[0][Id]         | a
items[1][Name]       | Name 2
items[1][Id]         | b

your payload should have looked like this:

items[0].Name       | Name 1
items[0].Id         | a
items[1].Name       | Name 2
items[1].Id         | b

Unfortunately with jQuery it can be quite frustrating to achieve this payload. For this reason I would recommend that you use a JSON payload if you want to send complex objects/arrays to your server with AJAX:

$.ajax({
    type: 'POST',
    url: '/myurl/myAction',
    data: JSON.stringify({ items: myData }),
    contentType: 'application/json',
    error: function (err) {
        alert("error - " + err);
    }
});

Things to notice:

  • data: JSON.stringify({ items: myData }) instead of data: { items: myData }
  • Added contentType: 'application/json'
  • Gotten rid of dataType: 'json'

Now your payload looks like this:

{"items":[{"id":"a","name":"Name 1"},{"id":"b","name":"Name 2"}]}

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)