0

Model binding is not working the way I thought it would. I thought I could just make an array of objects and pass that to $.post but no, not that easy.

This is what I want to do

var a=new Array();
a[0]={
    Name:"Eric",
    Email:"eric@yahoo.com"
}

a[1]={
    Name:"Peter",
    Email:"peter@gmail.com"
}

$.post("/Home/SendPersons", a, function (data, status) {
    $("#someid").html(data);
});

and in my controller:

public ActionResult SendPersons(IList<Person> persons) {
    //Do stuff
    return PartialView("Persons");
}

but the parameter is null. How do I do this correctly?

tereško
  • 58,060
  • 25
  • 98
  • 150
jorx
  • 481
  • 5
  • 7
  • possible duplicate of [Post an Array of Objects via JSON to ASP.Net MVC3](http://stackoverflow.com/questions/4789481/post-an-array-of-objects-via-json-to-asp-net-mvc3) – Meryovi Jul 19 '13 at 23:09

1 Answers1

2

A couple things that you need to make sure of:

Per the link that Meryovi provided, make sure that the fields you are attempting to bind have all the appropriate { get; set; } fields as the ModelBinder will not work otherwise. (You can post your Person model in your question if you want someone to take a look at it.)

In addition, make sure you are sending a true JSON request. You can do this by writing the following code:

$.ajax({
    url: '/Home/SendPersons',
    type: 'POST',
    dataType: 'json',
    contentType: 'application/json',
    data: JSON.stringify({ persons: a }),
    success: function (data) {
        $('#someid').html(data);
    },
    error: function (jqXHR, textStatus, errorThrown) {
        // TODO - Implement if an error occurs.
    }
});

Modern browsers will implement the stringify method. Otherwise, use Nuget to bring in JSON2 which will provide the stringify method if you need to support older browsers.

Also, as a third sanity check, look at your data. Quite often, there is a mismatch between how the JSON data is structured and the model data.

JasCav
  • 34,458
  • 20
  • 113
  • 170