我正在使用ASP.Net MVC 3,根据支持的功能列表,我应该能够轻松地使用默认的JSON模型绑定。然而,我无法成功地将数组/集合从JSON绑定到操作方法参数。虽然我确实成功了将简单的JSON对象绑定正确。如果有专家能告诉我问题出在哪里,我将不胜感激。
以下是代码:
首先是服务器端代码:
// Action 方法
以下是代码:
首先是服务器端代码:
// Action 方法
public JsonResult SaveDiscount(IList<Discount> discounts)
{
foreach(var discount in discounts)
{
....
}
}
//视图模型
public class Discount
{
string Sku{get; set;}
string DiscountValue{get; set;}
string DiscountType{get; set;}
}
//客户端(jQuery/JS):
var discount = {};
var jsondatacoll = [];
$('#discountgrid tr').each(function () {
sku = $(this).find("td").eq(1).html();
discValue = $(this).find('.discval').val();
discType = $(this).find('.disctype').val();
discount = { Sku: sku, DiscountType: discType, DiscountValue: discValue};
jsondatacoll.push(discount);
}
})
if (jsondatacoll.length > 0) {
var catalogDiscount = JSON.stringify(jsondatacoll);
$.ajax(
{
url: '/url/savediscount',
type: 'POST',
data: catalogDiscount,
dataType: 'json',
contentType: 'application/json; charset=utf-8',
success: function (data, textStatus, jqXHR) {
...
},
error: function (objAJAXRequest, strError) {
...
}
}
); //ajax
}
我在 Fiddler 中检查了 JSON 负载,它看起来像下面这样:
[
{"Sku":"sku1","DiscountType":"type1","DiscountValue":"10"},
{"Sku":sku2","DiscountType":"type1","DiscountValue":"12"},
{"Sku":"sku3","DiscountType":"type2","DiscountValue":"40"}
]
在服务器端,我看到IList<Discount>
discounts 已经被填充了3个空的Discount
对象 - 这意味着属性为null,但是折扣参数的长度为3。