加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > asp.Net > 正文

asp.net-mvc – ASP.Net MVC 3 – JSON模型绑定到数组

发布时间:2020-12-16 00:33:59 所属栏目:asp.Net 来源:网络整理
导读:我在ASP.Net MVC 3,并且在支持的功能列表中,我应该能够获得默认的json模型绑定工作开箱即用。然而,我没有成功地将json的数组/集合绑定到action方法参数。虽然我确实得到了简单的json对象绑定工作权限。非常感谢,如果一位专家在这里可以告诉我我做错了什
我在ASP.Net MVC 3,并且在支持的功能列表中,我应该能够获得默认的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","DiscountValue":"12"},{"Sku":"sku3","DiscountType":"type2","DiscountValue":"40"}
]

而在服务器端,我确实看到了IList< Discount>折扣已经填充了3个空的折扣对象 – 这意味着属性为null,但折扣参数的长度为3。

解决方法

正如 Cresnet Fresh在对问题的评论中正确指出的那样,模型属性必须标注为public。

所以修改折扣类如下解决了这一点。

public class Discount
{
    public string Sku{get; set;}
    public string DiscountValue{get; set;}
    public string DiscountType{get; set;}

}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读