.NET MVC: how to get the model binder to assign null to a list property?

 ̄綄美尐妖づ 提交于 2019-12-11 10:31:46

问题


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).


回答1:


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



回答2:


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.



来源:https://stackoverflow.com/questions/14203150/net-mvc-how-to-get-the-model-binder-to-assign-null-to-a-list-property

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!