问题
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