我有一个需要绑定到接口的场景 - 为了创建正确的类型,我有一个自定义模型绑定器,知道如何创建正确的具体类型(可能不同)。
但是,创建的类型永远不会正确填写字段。我知道我在这里遗漏了一些令人眼花缭乱的东西,但是任何人都可以告诉我为什么或者至少我需要做什么才能让模型绑定器继续进行它的工作并绑定属性?
public class ProductModelBinder : DefaultModelBinder
{
override public object BindModel (ControllerContext controllerContext, ModelBindingContext bindingContext)
{
if (bindingContext.ModelType == typeof (IProduct))
{
var content = GetProduct (bindingContext);
return content;
}
var result = base.BindModel (controllerContext, bindingContext);
return result;
}
IProduct GetProduct (ModelBindingContext bindingContext)
{
var idProvider = bindingContext.ValueProvider.GetValue ("Id");
var id = (Guid)idProvider.ConvertTo (typeof (Guid));
var repository = RepositoryFactory.GetRepository<IProductRepository> ();
var product = repository.Get (id);
return product;
}
}
我的案例中的模型是一个具有IProduct属性的复杂类型,它是我需要填写的那些值。
型号:
[ProductBinder]
public class Edit : IProductModel
{
public Guid Id { get; set; }
public byte[] Version { get; set; }
public IProduct Product { get; set; }
}
答案 0 :(得分:0)
ModelBinder正在以递归方式工作,所以您需要做的是实现自定义模型绑定器,覆盖方法onCreate和BindModel。
protected override object CreateModel(ControllerContext controllerContext, ModelBindingContext bindingContext, Type modelType)
{
// get actual type of a model you want to create here
return Activator.CreateInstance(type);
}
public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
{
// here our CreateModel method will be called
var model = base.BindModel(controllerContext, bindingContext);
// we will get actual metadata for type we created in the previous line
var metadataForItem = ModelMetadataProviders.Current.GetMetadataForType(() => model, model.GetType());
// and then we need to create another binding context and start model binding once again for created object
var newModelBindingContext = new ModelBindingContext
{
ModelName = bindingContext.ModelName,
ModelMetadata = metadataForItem,
ModelState = bindingContext.ModelState,
PropertyFilter = bindingContext.PropertyFilter,
ValueProvider = bindingContext.ValueProvider
};
return base.BindModel(controllerContext, newModelBindingContext);
}
希望有所帮助。