Asp.net-Mvc
ASP.Net MVC 3 - JSON 模型綁定到數組
我在 ASP.Net MVC 3 上,按照 at 中支持的功能列表,我應該能夠獲得開箱即用的預設 json 模型綁定。但是我還沒有成功地將一個數組/集合從 json 綁定到 action 方法參數。雖然我確實讓簡單的 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對象——這意味著屬性為空,但折扣參數的長度為 3。
正如Cresnet Fresh在對問題的評論中正確指出的那樣,模型屬性必須標記為公開。
所以
Discount如下修改類解決了這個問題。public class Discount { public string Sku{get; set;} public string DiscountValue{get; set;} public string DiscountType{get; set;} }
雖然@thanikkal回答了這個特定問題,但我有相同的症狀和非常相似的設置。
而不是我的模型中的
publicor{ get; set; }導致模型綁定不起作用,它實際上是我的jQuery方法!(生!)我正在使用
$.post(不起作用)而不是$.ajax.不工作:
$.post("/Games/Action", { "userId": "1", "listName": [ { "fooId": "2", "barId": "99" } ] }, 'json', true );這些值在 Form.Data[] 中,但未正確映射。
作品:
$.ajax( { url: '/Games/Action', type: 'POST', data: JSON.stringify({ userId: "1", listName: [ { fooId: 2, barId: 99 } ] }), dataType: 'json', contentType: 'application/json; charset=utf-8', success: function (data, textStatus, jqXHR) { console.log(data); }, error: function (objAJAXRequest, strError) { console.log(data); } });所有值都正確映射。
浪費了幾個小時,希望這對其他人有所幫助。