我有一个从接口派生出来的对象。我想使用显示模板和编辑器template.Display模板工作得很好。但是编辑器模板工作不太好,well.It不明白它说的“不能创建接口的实例”。我有一个定制的模型活页夹。但它真的是假的。
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; }
}发布于 2013-12-22 16:07:56
没有考虑为什么你需要这个(我认为这是一个糟糕的设计,把接口作为控制器方法的参数)。我认为最简单的解决方案是使用string属性ImplementedType扩展ImplementedType接口。
public interface IExample
{
string type {get;}
int number { get; set; }
}执行情况:
public class ExampleType1 : IExample
{
public string type
{ get { return "ExampleType1"; } }
public int number { get; set; }
public string tip1 { get; set; }
}和范本:
var type = (string)bindingContext.ValueProvider.GetValue("type");
if (type == "ExampleType1")
{
//create new instance of exampletype1.
}https://stackoverflow.com/questions/20730993
复制相似问题