So to pass the information using AJAX, you need to supply two parameters: dataType and contentType. (I suppose dataType is optional, but if you're expecting JSON back it's better to supply it.). The contentType, however, lets MVC [the ModelBinder] know the incoming request isn't just a string, but that it's an object that needs to be deserialized back into objects.
with that said, something like the following should work for your circumstance:
// This is your to-be-sent data'
// However you collect it, but for now we're storing it as a plain object.
var jso = { models: [{ "Id": null, "Start": "2014-06-11T12:17:52.452Z", "End": "2014-06-11T12:17:52.452Z", "Name": "test", "Status": "test" }] }
// Here we turn it into JSON
var json = JSON.stringify(jso);
// And now we send it off to the controller/action:
$.ajax({
url: '@Url.Action("SomeAction","SomeController")',
type: 'POST',
data: json, // pass of data serialized
dataType: 'json', // expecting json back
contentType: 'application/json; charset=utf-8', // hey ModelBinder, deserialize this!
})/* handle the Deferred callbacks (.done, .fail, .always) */;
Then, in your controller:
public class SomeController : Controller
{
[HttpPost]
public JsonResult SomeAction(IList<MyModel> models)
{
// Should pass now
if (ModelState.IsValid)
{
// Handle it and return back the response
// Given the above, you have something like the following now
// assigned to "models":
// models = new List<MyModel> {
// new MyModel {
// Id = null,
// Start = new DateTime(2014, 11, 6, 12, 17, 52),
// End = new DateTime(2014, 11, 6, 12, 17, 52),
// Name = "test",
// Status = "test"
// }
// };
return Json(new {Models = models }); // just to see it come back
}
return Json(new { Error = true, Message = "Invalid model" });
}
}
Working example can be seen On GitHub by the way.
dataTypeparameter so MVC knows it's JSON incoming and not just a string value.dataType: "json"and its weird, when I change my controller to acceptFoo(object models)the object is a list that contains a string"[{\"Id\":null,\"StartDate\":\"2014-06-11T13:08:19.483Z\",\"EndDate\":\"2014-06-11T13:08:19.483Z\",\"Name\":\"test\",\"Status\":\"test\"}]", it seems like ModelBinding is broken or something, since when I put real model, I get null.