【问题标题】:Issue With Custom Collection Model Binder in MVC 3MVC 3 中的自定义集合模型绑定器问题
【发布时间】:2012-05-11 22:36:25
【问题描述】:

我在 MVC 中创建模型绑定器时遇到问题。

我的目标操作如下:

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

我创建了一个自定义模型绑定器并使用以下代码注册它:

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

附加调试器后,我可以看到CollectionModelBinder's CreateModel 方法正在被调用。但是,当执行到控制器的action方法时,accounts参数为null。

有什么问题?

我的模型活页夹看起来像:

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}};
    }
}

更新:

这是DefaultModelBinder. 的问题在调用CreateModel 之后,调用了另一个内部方法UpdateCollection,它有效地取消了CreateModel. 创建的集合解决方案是推出我自己的实现IModelBinder. IModelBinder.BindModel 唯一缺少的参数是 modelType,,它很容易获得:

public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
{
    var type = bindingContext.ModelType;
    //...
}

【问题讨论】:

    标签: c# asp.net-mvc-3 model-binding modelbinders


    【解决方案1】:

    这是DefaultModelBinder. 的问题在调用CreateModel 之后,调用了另一个内部方法UpdateCollection,它有效地取消了CreateModel. 创建的集合解决方案是推出我自己的实现IModelBinder. IModelBinder.BindModel 唯一缺少的参数是 modelType,,它很容易获得:

    public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
    {
        var type = bindingContext.ModelType;
        //...
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-04-27
      • 1970-01-01
      • 2011-12-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多