views:

25

answers:

1

I have a pretty complex object with numerous datatypes. A few datatypes are Lists (LazyLists to be exact).

In my form, I let the user enter up to, say 3 items for this list and my form input names correspond appropriately:

myObj[0].Name
myObj[0].Email
...consectuviely...
myObj[2].Name
myObj[2].Email

If the user decides to only enter one object's values, that's fine with me, but I do not want a list like this:

myObjList[0] = {Name = "joe", Email = "[email protected]"}
myObjList[1] = {Name = null, Email = null}
myObjList[2] = {Name = null, Email = null}

The problem I've found is that the DefaultModelBinder will create the object first then just not bind the properties - leaving the object with null properties. In the case of a list, the UpdateCollection method doesn't seem to care, and just adds the objects while there are objects to add.

Any ideas? Is there something simple I'm missing?

A: 

This seems to work well. I bind the list normally, then I return only the items that are not equal to a new EventContact (where all the fields are null).

public class EventContactListModelBinder : IModelBinder
{
    #region IModelBinder Members

    public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
    {
        LazyList<EventContact> contacts = (LazyList<EventContact>)ModelBinders.Binders.DefaultBinder.BindModel(controllerContext, bindingContext);
        var p = (from e in contacts
                 where !e.Equals(new EventContact())
                 select e).AsQueryable();
        return new LazyList<EventContact>(p);
    }

    #endregion
}

I'm still open to a more elegant solution if one exists :)

Dan