1

我有一个这样的模型:

class Model {
    public IList<Item> Items { get; set; }
}

class Item { public int Id { get; set; } }

我正在向以模型作为参数的操作方法发送请求。该请求包含以下键值对:" Items=" (i. e. Items=null)。默认模型绑定器将 Items 设置为 1null项的列表,我希望列表属性本身为null(或至少为空)。

有没有办法做到这一点?

显然,我可以进行某种自定义模型绑定,但我更喜欢使用默认模型绑定器的解决方案(也许修改请求的格式)。

4

2 回答 2

0

假设您使用 jQuery,我将扩展它以能够将表单序列化为对象

$.fn.serializeObject = function()
{
var o = {};
var a = this.serializeArray();
$.each(a, function() {
    if (o[this.name] !== undefined) {
        if (!o[this.name].push) {
            o[this.name] = [o[this.name]];
        }
        o[this.name].push(this.value || '');
    } else {
        o[this.name] = this.value || '';
    }
});
return o;
};

然后我可以简单地将表单放入一个变量中:

var data = $('form').serializeObject();

做我的测试以确定我是否要删除属性

if(true){
    delete data.Items;
}

然后正常继续使用ajax提交数据。

于 2013-01-07T20:24:00.210 回答
0

您可以使用您想要的行为向类添加一个属性。

public property MySanitizedItemsList
{
    get
    {
        if (Items.Length == 1 && Items[0] == null)
            return null
        else
            return Items;
    }
}
于 2013-01-07T20:04:48.363 回答