문제

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