我有一个模型,它看起来像这样:
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。当我尝试在操作方法中调用UpdateModel<MyModel>(model);
时,它会抛出“无法更新MyModel类型的模型。”
答案 0 :(得分:0)
好的,我明白了。我必须在我的模型类声明旁边添加binder属性,以确保在将模型传递给action方法时调用binder。
[ModelBinder(typeof(MyModelBinder))]
public class MyModel
{
...
}
这并不明显,因为即使没有此属性,仍会调用自定义绑定器,但由于某种原因,其输出未发送到操作,而是使用默认绑定器的输出。