.NET MVC: how to get the model binder to assign nu

2019-07-27 06:32发布

I have a model like so:

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

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

I am sending a request to an action method that takes a Model as a parameter. The request contains the following key-value pair: "Items=" (i. e. Items=null). The default model binder sets Items to be a list of 1 null item, where I want the list property itself to be null (or at least empty).

Is there any way to accomplish this?

Obviously, I could do some sort of custom model binding, but I'd prefer a solution that would work using the default model binder (perhaps modifying the formatting of the request).

2条回答
太酷不给撩
2楼-- · 2019-07-27 07:09

You could add a property to the class with the behavior you want.

public property MySanitizedItemsList
{
    get
    {
        if (Items.Length == 1 && Items[0] == null)
            return null
        else
            return Items;
    }
}
查看更多
干净又极端
3楼-- · 2019-07-27 07:10

Assuming you use jQuery, I would extend it to be able to serialize the form to object

$.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;
};

Then I could simply get the form into a variable:

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

Do my test to know if I want to delete a property

if(true){
    delete data.Items;
}

Then proceed normally with submitting the data with ajax.

查看更多
登录 后发表回答