我在ASP.Net MVC 3中,並支持at中的功能列表,我應該能夠獲得默認的json模型綁定。不過,我還沒有成功地從json綁定數組/集合到action方法參數。儘管我確實得到了簡單的json對象綁定,如果這裏的專家能告訴我我做錯了什麼,我將不勝感激。ASP.Net MVC 3 - JSON模型綁定到數組
下面是代碼:
服務器端代碼第一:
//操作方法
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
}
我做檢查的JSON有效載荷的小提琴手,它看起來象下面這樣:
[
{"Sku":"sku1","DiscountType":"type1","DiscountValue":"10"},
{"Sku":sku2","DiscountType":"type1","DiscountValue":"12"},
{"Sku":"sku3","DiscountType":"type2","DiscountValue":"40"}
]
和服務器端我看到的IList<Discount>
折扣已經填充了3個空Discount
對象 - 這意味着該屬性爲null但折扣參數的長度爲3
您的模型的屬性應該標記爲「public」。錯字或疏忽? – 2011-03-12 18:49:36
哇!這是一個疏忽!你想要輸入這個答案,以便我可以標記它嗎? :) – thanikkal 2011-03-12 18:55:23
感謝您的帖子的其餘部分是正確的(除了那些缺少'公共'),我注意到使用JSON.stringify設置contentType,它使所有不同。與此掙扎了好幾個小時!謝謝! – 2011-09-19 18:10:14