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

2

1

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

Calie answered 7/1, 2013 at 20:1 Comment(4)
@MystereMan I am not using a listBox. I am making an ajax request and thus have direct control over the key-value pairsCalie
@Calie - If that's the case, what's stopping you from not sending Items if it's empty? Can we see the AJAX request code?Goren
@Goren the values in the request get to the browser in JSON format (from an earlier request). I then do a post with these same values. This uses common JS code, so I'd rather not modify it to handle the Items property specially.Calie
@Calie - Why not modify it to simply not post empty values? If that's your requirement, shouldn't it be the same everywhere?Bolyard
O
0

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;
    }
}
Ordination answered 7/1, 2013 at 20:4 Comment(0)
D
0

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.

Diabetic answered 7/1, 2013 at 20:24 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.