tha*_*kal 17 asp.net-mvc json model-binding asp.net-mvc-3
我在ASP.Net MVC 3上,并且通过at中支持的功能列表,我应该能够获得默认的json模型绑定开箱即用.但是我还没有成功地将数组/集合从json绑定到action方法参数.虽然我确实得到了简单的json对象绑定正常工作.如果这里的专家可以告诉我我做错了什么,我将不胜感激.
这是代码:
服务器端代码优先:
//动作方法
public JsonResult SaveDiscount(IList<Discount> discounts)
{
foreach(var discount in discounts)
{
....
}
}
Run Code Online (Sandbox Code Playgroud)
//查看模型
public class Discount
{
string Sku{get; set;}
string DiscountValue{get; set;}
string DiscountType{get; set;}
}
Run Code Online (Sandbox Code Playgroud)
//客户端(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
}
Run Code Online (Sandbox Code Playgroud)
我确实检查了fiddler中的json有效负载,它看起来如下所示:
[
{"Sku":"sku1","DiscountType":"type1","DiscountValue":"10"},
{"Sku":sku2","DiscountType":"type1","DiscountValue":"12"},
{"Sku":"sku3","DiscountType":"type2","DiscountValue":"40"}
]
Run Code Online (Sandbox Code Playgroud)
在服务器端,我确实看到IList<Discount>
折扣已经填充了3个空Discount
对象 - 意味着属性为null但折扣参数的长度为3.
tha*_*kal 14
正如Cresnet Fresh在对问题的评论中正确指出的那样,模型属性必须标记为公开.
所以修改Discount
类如下解决了这个问题.
public class Discount
{
public string Sku{get; set;}
public string DiscountValue{get; set;}
public string DiscountType{get; set;}
}
Run Code Online (Sandbox Code Playgroud)
Gra*_*amF 11
虽然@thanikkal回答了这个问题,但我的症状和设置非常相似.
而不是我的模型中的public
或{ get; set; }
导致模型绑定不起作用它实际上是我的jQuery方法!(RAWR!)
我正在使用$.post
(哪些不起作用)而不是$.ajax
.
不起作用:
Run Code Online (Sandbox Code Playgroud)$.post("/Games/Action", { "userId": "1", "listName": [ { "fooId": "2", "barId": "99" } ] }, 'json', true );
值位于Form.Data []中,但未正确映射.
作品:
Run Code Online (Sandbox Code Playgroud)$.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); } });
所有值都正确映射.
失去了几个小时到这一个,希望这有助于其他人.
归档时间: |
|
查看次数: |
13478 次 |
最近记录: |