2011-07-26 56 views
1

我有一个模型传递JS对象层次结构控制器

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

为什么会发生?我究竟做错了什么?如何将对象数组传递给动作?我试过使用jquery.serialize()serializeArray()甚至$.toDictionary()方法描述here

那不是帮助

回答

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功能工作。

+0

我认为JSON.stringify在IE – Agzam

+0

的某些版本中不起作用,如果我们从大专角度来看:您的$ .ajax和$ .post之间有什么区别。只有contentType? – Agzam

+0

@Agzam,正确的,我已经更新了我的答案。您将需要为原本不支持“JSON.stringify”方法的传统浏览器添加'json2.js'脚本。而且,是的,'$ .post'和'$ .ajax'之间的唯一区别就是后者允许你设置请求内容类型头文件'contentType'。 –