2012-03-02 73 views
2

可能重复:
Passing a collection of objects to MVC controller using $.postMVC 3如何将自定义JS对象传递给控制器​​?

我有一个类:

public class MyClass 
{ 
    public int BookID { get; set; } 

    public List<SelectedBookFormat> SelectedFormats { get; set; } 

    public SelectedBasketBook() 
    { 
     SelectedFormats = new List<SelectedBookFormat>(); 
    } 
} 

public class SelectedBookFormat 
{ 
    public int ID { get; set; } 
    public int Quantity { get; set; } 
    public double Price { get; set; } 
} 

和动作:

public JsonResult Add(MyClass model) 
{ 
... 
} 

我想从客户端生成的类柱:

(I生成类对象,然后我使用JSON.stringify()方法)

model {"BookID":"1","SelectedFormats":[{"ID":"4","Quantity":"34","Price":"44"},{"ID":"1","Quantity":"1","Price":"11"}]} 

JS:

$.post('/Add', { 
       model : JSON.stringify({ BookID: '@Model.BookID', 
             SelectedFormats : formatsTab }) }, 
     function(res){} 
       }); 

但传递的对象在服务器端为空,为什么?

回答

3
var data = {}; 
data.BookId = 4; 

var format = { }; 
format.ID = 3; 
format.Quantity = 4; 
format.Price = 2.2; 

data.SelectedFormats = []; 
data.SelectedFormats.push(format); 

return $.ajax({ 
    type: 'POST', 
    url: 'YourController/YourAction', 
    dataType: 'json', 
    traditional: true, 
    data: { 
     model: data 
    } 
}); 

对我的救命恩人一直traditional: true

Ps。在服务器端似乎没有必要属性,所以你可以将它们改为字段,因此用小写字母书写。然后它会匹配JS的写作风格,并且在服务器端仍然有效。这当然是品味的问题。

+0

嗯''BookID'正确传递,但该列表有0项的数量。如果我将'MyClass'从List 更改为'SelectedBookFormat []',它将为null – Tony 2012-03-02 09:28:12

相关问题