我有一个从接口派生的对象。我想使用显示模板和编辑器模板。显示模板工作得很好。但编辑器模板不能很好地工作。它不理解它说“不能创建一个接口的实例”。 我有一个自定义模型活页夹。但它确实是虚拟的。接口模型绑定 - MVC 4
protected override object CreateModel(ControllerContext controllerContext,ModelBindingContext bindingContext, Type modelType)
{
if (modelType.Equals(typeof(IExample)))
{
Type instantiationType = typeof(ExampleType1);
var obj = Activator.CreateInstance(instantiationType);
bindingContext.ModelMetadata = ModelMetadataProviders.Current.GetMetadataForType(null, instantiationType);
bindingContext.ModelMetadata.Model = obj;
return obj;
}
return base.CreateModel(controllerContext, bindingContext, modelType);
}
我该如何为每个从IExample派生的类做到这一点?有任何想法吗?
[HttpGet]
public ActionResult Index()
{
MyModel model = new MyModel();
model.inter = new ExampleType1();
model.inter.number = 50;
return View(model);
}
[HttpPost]
public ActionResult Index(MyModel model)
{
//*-*-* I want to get it here.
return View();
}
public class MyModel
{
public IExample inter { get; set; }
}
public interface IExample
{
int number { get; set; }
}
public class ExampleType1 : IExample
{
public int number { get; set; }
public string tip1 { get; set; }
}
public class ExampleType2 : IExample
{
public int number { get; set; }
public string tip2 { get; set; }
}
你说的意思是什么? “我怎么能做到这一点从的IExample任何想法派生的每个类?”。另外,我认为moel binder的部分是错误的。应该是:bindingContext.ModelMetadata = ModelMetadataProviders.Current.GetMetadataForType(null,modelType); – Botis
我只为ExampleType1创建了实例。 类型instantiationType = typeof(ExampleType1);在我的索引操作中,我说IExample是ExampleType1的类型。但我可以说它是ExampleType2。 我也想为ExampleType2创建一个实例。但我想要做到这一点。我可以从IExample派生更多的类。 – user3127359
类似的问题在这里:http://stackoverflow.com/questions/8276627/how-can-i-build-a-custom-model-binder-which-will-return-different-types-of-model。但是我同意Botis的说法,可能有更好的方法。 –