对对象使用JSON解析会导致包含一个空项而不是null的列表

时间:2016-08-10 20:36:32

标签: c# json asp.net-mvc

我知道这个问题的标题有点令人困惑。我遇到的问题是我在使用JSON解析后将一个对象传递给我的控制器。该对象包含列表,这些列表被传递到控制器,其计数为1项为null,而不是整个属性为null。

型号:

public class QboModel
{
    public int Id { get; set; }
    public List<Customer> Customers { get; set; }
    public List<Invoice> Invoices { get; set; }
}

查看:

 @{ var qboModel = new QboModel { Id = 0, Customers = null, Invoices = null }; }
 <a href="#" onclick="refresh('new JavaScriptSerializer().Serialize(qboModel)')">Refresh</a>

脚本:

function refresh(qboModel) {
    $.post(url, { qboModel: JSON.parse(qboModel) }, function(data) {
        // Do stuff
    });
}

控制器:

public async Task<JsonResult> Refresh(QboModel qboModel)
{
    // qboModel.Id = 0
    // qboModel.Customers = Count = 1, [0] null
    // qboModel.Invoices = Count = 1, [0] null
}

我希望我已经正确地解释了这一点。基本上我做不到:

if (qboModel.Customers == null) return;

相反,我必须做类似的事情:

foreach(var customer in qboModel.Customers) {
    if (customer == null) return;
}

0 个答案:

没有答案