I have a model
public class Foo{
public int Id{get;set;}
public string Name {get; set;}
public DateTime Date {get; set;}
public bool IsActive {get;set;}
public List<Item> Items {get;set;}
}
public class Item{
public int Id {get;set;}
public string Name {get; set;}
public Foo Foo {get;set;}
}
And in my javascript I do that:
var items = new Array();
$("#itemsSelector").each(function () {
items.push({Id: $(this).val(), Name: $(this).text() })
}
var id = $("#id").val();
var title = $("#title").val();
var date = $("#dateTimePicker").val();
var isActive = $("#msActive").val();
$.post("SaveFoo", {Id: id, Name:title, Date:date, IsActive: isActive, Items:items })
Action method signature looks like that:
[HttpPost]
public JsonResult SaveFoo(Foo foo) {
// Now. here it passes correct Id, Name, Date and bool parameter
// And even passes the correct number of Foo.Items
// The only thing that bothers me -
// all the properties of every Item is either null or zero!
}
Why is that happening? What am I doing wrong? How to pass the objects array to the action? I’ve tried to use jquery.serialize() and serializeArray()and even $.toDictionary() method described here.
That’s not helping
Have you tried a JSON request? It works much better with complex properties and collections:
And if you need to support older browsers you might need to include the json2.js script so that the
JSON.stringifyfunction works.