我需要创建一个基于派生类型的动态输入表单,但是当传递给控制器的 POST 方法时,我无法正确绑定复杂的属性。其他属性绑定很好。这是我所拥有的一个人为的例子:
模型
public abstract class ModelBase {}
public class ModelDerivedA : ModelBase
{
public string SomeProperty { get; set; }
public SomeType MySomeType{ get; set; }
public ModelDerivedA()
{
MySomeType = new SomeType();
}
}
public class SomeType
{
public string SomeTypeStringA { get; set; }
public string SomeTypeStringB { get; set; }
}
自定义模型绑定器
活页夹基于这个答案:多态模型绑定
public class BaseViewModelBinder : DefaultModelBinder
{
protected override object CreateModel(ControllerContext controllerContext, ModelBindingContext bindingContext, Type modelType)
{
var typeValue = bindingContext.ValueProvider.GetValue("ModelType");
var type = Type.GetType(
(string)typeValue.ConvertTo(typeof(string)),
true
);
if (!typeof(ModelBase).IsAssignableFrom(type))
{
throw new InvalidOperationException("The model does not inherit from mode base");
}
var model = Activator.CreateInstance(type);
bindingContext.ModelMetadata = ModelMetadataProviders.Current.GetMetadataForType(() => model, type);
return model;
}
}
控制器
[HttpPost]
public ActionResult GetDynamicForm([ModelBinder(typeof(BaseViewModelBinder))] ModelBase model)
{
// model HAS values for SomeProperty
// model has NO values for MySomeType
}
查看摘录
@Html.Hidden("ModelType", Model.GetType())
@Html.Test(Model);
JavaScript
该表单是使用$.ajax
using发布data: $(this).serialize()
的,如果我调试它会显示正确的填充表单数据。
所有属性都填充在模型中,不包括SomeType
. 我需要改变什么来填充它们?
谢谢