【问题标题】:Custom binder works fine, but the model is not updated自定义活页夹工作正常,但模型未更新
【发布时间】:2013-02-12 22:48:11
【问题描述】:

我有一个模型,它看起来像这样:

public class MyModel {
   public List<SomeBaseClass> list {get; set;}
   public string SomeProperty {get; set;}
}

其中SomeBaseClass 实际上是一个基类,列表可以包含不同类型的项目,但所有这些类型都继承自SomeBaseClass

为了确保我的模型正确绑定,我必须实现一个自定义绑定器,该绑定器根据表单数据填充模型。

public class MyModelBinder: DefaultModelBinder
{
   public override object BindModel(ControllerContext cntxt, ModelBindingContext bindingContext)
   {
        var model = new MyModel {
            list = new List<SomeBaseClass>(),
            SomeProperty = ...
        };

        ... // some data mangling and type twisting here

        return model; // here the debugger shows that the model's list is populated properly based on the form data.
    }
}

但是当一个视图调用一个动作时,我的模型是不完整的:

public string SomeAction(MyModel model) { // <~~ It calls the custom binder before coming to here, which is correct
   // As the result, the model variable is an instance of MyModel, but the list is null
   return "somethhing";
}

在 action 方法中,我收到模型对象,其 list 属性设置为 null。这很奇怪,因为绑定器被正确调用并且它正确地填充了模型及其所有属性。

我不知道我做错了什么。

P.S.当我尝试在 action 方法中调用 UpdateModel&lt;MyModel&gt;(model); 时,它会抛出“无法更新 MyModel 类型的模型。”

【问题讨论】:

    标签: c# model-view-controller model-binding


    【解决方案1】:

    好的,我明白了。我必须在模型类声明旁边添加 binder 属性,以确保在将模型传递给 action 方法时调用 binder。

    [ModelBinder(typeof(MyModelBinder))]
    public class MyModel
    {
    ...
    }
    

    这并不明显,因为即使这个属性不存在,自定义 binder 仍然会被调用,但由于某种原因它的输出没有发送到 action,而是使用默认 binder 的输出。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-10-21
      • 2016-01-25
      • 2014-04-06
      • 2020-01-05
      • 1970-01-01
      • 1970-01-01
      • 2016-02-04
      • 1970-01-01
      相关资源
      最近更新 更多