将js-objects层次结构传递给Controller

时间:2011-07-26 17:50:39

标签: jquery asp.net-mvc-3

我有一个模特

  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;}
 }

在我的javascript中,我这样做:

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 })

动作方法签名如下:

 [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!
 }

为什么会这样?我究竟做错了什么?如何将objects数组传递给action?我尝试使用jquery.serialize()serializeArray()甚至$.toDictionary()方法描述here

那没有帮助

1 个答案:

答案 0 :(得分:4)

您是否尝试过JSON请求?它可以更好地处理复杂的属性和集合:

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 = $('#isActive').val();

$.ajax({
    url: 'SaveFoo',
    type: 'POST',
    contentType: 'application/json; charset=utf-8',
    data: JSON.stringify({
        id: id, 
        name: title, 
        date: date, 
        isActive: isActive, 
        items: items 
    }),
    success: function(result) {

    }
});

如果您需要支持旧浏览器,则可能需要包含json2.js脚本,以便JSON.stringify功能正常工作。