I'm having an issue creating a model binder in MVC.

The action that I'm targeting looks like:

public ActionResult GetAccounts (ICollection<Account> accounts ){}

I created a custom model binder and registered it with the following code:

ModelBinders.Binders.Add(typeof(ICollection<Account>),new CollectionModelBinder());

With a debugger attached, I can see that the CollectionModelBinder's CreateModel method is being called. However, when execution reaches the action method of the controller, the accounts parameter is null.

What's the issue?

My model binder looks like:

public class CollectionModelBinder : DefaultModelBinder
{
    protected override object CreateModel(ControllerContext controllerContext, ModelBindingContext bindingContext, Type modelType)
    {
        return new List<Account> {
            new Account {Id = 1}, 
            new Account {Id = 2}, 
            new Account {Id = 3}};
    }
}

UPDATE:

This was a problem with DefaultModelBinder. After CreateModel was called, another internal method, UpdateCollection was called, which effectively nulled out the collection that was created by CreateModel. The solution was to roll my own implementation of IModelBinder. The only argument that's missing on IModelBinder.BindModel is the modelType, which is easy to get:

public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
{
    var type = bindingContext.ModelType;
    //...
}
有帮助吗?

解决方案

This was a problem with DefaultModelBinder. After CreateModel was called, another internal method, UpdateCollection was called, which effectively nulled out the collection that was created by CreateModel. The solution was to roll my own implementation of IModelBinder. The only argument that's missing on IModelBinder.BindModel is the modelType, which is easy to get:

public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
{
    var type = bindingContext.ModelType;
    //...
}
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top