[英]Issue With Custom Collection Model Binder in MVC 3
I'm having an issue creating a model binder in MVC. 我在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. 附加了调试器后,我可以看到正在调用CollectionModelBinder's CreateModel
方法。 However, when execution reaches the action method of the controller, the accounts parameter is null. 但是,当执行到达控制器的操作方法时,accounts参数为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.
这是DefaultModelBinder.
的问题DefaultModelBinder.
After CreateModel
was called, another internal method, UpdateCollection
was called, which effectively nulled out the collection that was created by CreateModel.
调用CreateModel
之后,另一个内部方法UpdateCollection
被调用,该方法有效地使CreateModel.
创建的集合无效CreateModel.
The solution was to roll my own implementation of IModelBinder.
解决方案是推出我自己的IModelBinder.
实现IModelBinder.
The only argument that's missing on IModelBinder.BindModel
is the modelType,
which is easy to get: 唯一缺少的唯一参数IModelBinder.BindModel
是modelType,
这是很容易得到:
public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
{
var type = bindingContext.ModelType;
//...
}
This was a problem with DefaultModelBinder.
这是DefaultModelBinder.
的问题DefaultModelBinder.
After CreateModel
was called, another internal method, UpdateCollection
was called, which effectively nulled out the collection that was created by CreateModel.
调用CreateModel
之后,另一个内部方法UpdateCollection
被调用,该方法有效地使CreateModel.
创建的集合无效CreateModel.
The solution was to roll my own implementation of IModelBinder.
解决方案是推出我自己的IModelBinder.
实现IModelBinder.
The only argument that's missing on IModelBinder.BindModel
is the modelType,
which is easy to get: 唯一缺少的唯一参数IModelBinder.BindModel
是modelType,
这是很容易得到:
public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
{
var type = bindingContext.ModelType;
//...
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.