这是我的自定义模型绑定器,用于实例化派生类。
public class LocationModalBinder : DefaultModelBinder
{
protected override object CreateModel(ControllerContext controllerContext, ModelBindingContext bindingContext,
Type modelType)
{
var type = bindingContext.ModelName + "." + "type";
Type typeToInstantiate;
switch ((string) bindingContext.ValueProvider.GetValue(type).RawValue)
{
case "store":
{
typeToInstantiate = typeof (Store);
break;
}
case "billing":
{
typeToInstantiate = typeof(LocationReference);
break;
}
case "alternate":
{
typeToInstantiate = typeof(Address);
break;
}
default:
{
throw new Exception("Unknown location identifier.");
}
}
return base.CreateModel(controllerContext, bindingContext, typeToInstantiate);
}
}
问题是它不绑定子类型的属性。仅限基本类型Location
上的属性。这是为什么?
答案 0 :(得分:1)
我认为调用return base.CreateModel
可以正常尝试。
我通过在return base.CreateModel
行之前添加以下内容来解决它:
bindingContext.ModelMetadata = ModelMetadataProviders.Current.GetMetadataForType(null, typeToInstantiate);
答案 1 :(得分:0)
从这里做到了...... https://stackoverflow.com/a/9428558/221683
我不明白这种模型活页夹的例子有多少没有这些作业。
public class LocationModalBinder : DefaultModelBinder
{
protected override object CreateModel(ControllerContext controllerContext, ModelBindingContext bindingContext,
Type modelType)
{
var type = bindingContext.ModelName + "." + "type";
Type typeToInstantiate;
switch ((string) bindingContext.ValueProvider.GetValue(type).RawValue)
{
case "store":
{
typeToInstantiate = typeof (Store);
break;
}
case "billing":
{
typeToInstantiate = typeof(LocationReference);
break;
}
case "alternate":
{
typeToInstantiate = typeof(Address);
break;
}
default:
{
throw new Exception("Unknown location identifier.");
}
}
var model = Activator.CreateInstance(typeToInstantiate);
bindingContext.ModelMetadata = ModelMetadataProviders.Current.GetMetadataForType(null, typeToInstantiate);
bindingContext.ModelMetadata.Model = model;
return model;
}
}