0

I need to submit a list of users. I have a MVC controller

[HttpPost]
public JsonResult Handler(List<User> users) {
   ...
}

where User is

public class User {
    public string name { get; set; }
    public string email { get; set; }
}

in JavaScript I send the array by jquery

    var users = {};
    for (var i = 0; i < 3; i++) {
        users [i] = {
            name: "User " + i, 
            email: "user" + i + "@test.net"
        }
    }

   $.ajax({
        type: "POST",
        data: {
                users: users
        },
        url: "http://test.net/order/handler",
        success: callback
    });

I get the list with 3 items, but parameters name and email are NULL.

Where am I wrong?

tereško
  • 58,060
  • 25
  • 98
  • 150
podeig
  • 2,597
  • 8
  • 36
  • 60

3 Answers3

0

Have you tried adding [FromBody] to the parameter? Example:

[HttpPost]
public JsonResult Handler([FromBody] List<User> users) {
   ...
}

Also it's important to set the ContentType of your ajax POST so that the ModelBinder knows what to use:

$.ajax({
    type: "POST",
    data: {
            users: users
    },
    url: "http://test.net/order/handler",
    success: callback,
    contentType: 'application/json'
});

Another thing: You may be doing a Cross-domain ajax post which has several implications. You can consider using Fiddler to see what is really happening to your request and post an update so we can help you further.

Community
  • 1
  • 1
Peter
  • 14,221
  • 15
  • 70
  • 110
0

Isn't it because you should be creating an array and then add objects to it:

    var users = [];
    for (var i = 0; i < 3; i++) {
        var user = {
            name: "User " + i, 
            email: "user" + i + "@test.net"
        }

        users[i] = user;
    }

   $.ajax({
        type: "POST",
        data: {
                users: users
        },
        url: "http://test.net/order/handler",
        success: callback
    });
0

First of all you need to set valid json data:

var users = Array(), i;
for (i = 0; i < 3; i++) {
    users[i] =
    {
        name: "User " + i,
        email: "user" + i + "@test.net"
    };
}

Then send ajax request with dataType json:

$(document).ready(function() {
    $.ajax({
        type: "POST",
        dataType: 'json',
        data: {
            users: users
        },
        url: "http://test.net/order/handler",
        success: callback
    });
});
Igor
  • 171
  • 1
  • 8