Как насчет создания пользовательского связывателя модели:
public class BaseModelBinder : DefaultModelBinder
{
private Type _type;
protected override ICustomTypeDescriptor GetTypeDescriptor(ControllerContext controllerContext, ModelBindingContext bindingContext)
{
return TypeDescriptor.GetProvider(_type).GetTypeDescriptor(_type);
}
protected override object CreateModel(ControllerContext controllerContext, ModelBindingContext bindingContext, Type modelType)
{
var result = bindingContext.ValueProvider.GetValue("type");
if (result == null)
{
throw new Exception("please provide a valid type parameter");
}
_type = Type.GetType(result.AttemptedValue);
if (_type == null || !typeof(Base).IsAssignableFrom(_type))
{
throw new Exception("please provide a valid type parameter");
}
return Activator.CreateInstance(_type);
}
}
, который вы бы зарегистрировали в Application_Start
:
ModelBinders.Binders.Add(typeof(Base), new BaseModelBinder());
, и теперь вы можете выполнить следующее действие контроллера:
public ActionResult Foo(Base model)
{
...
}
Теперь, когда вы вызываете это действие, просто передайте дополнительный параметр type
, указывающий конкретный экземпляр, который вы хотите создать.Например:
http://localhost:1203/?type=MvcApplication1.Models.Alpha&Id=21EC2020-3AEA-1069-A2DD-08002B30309D&Name=Test&Description=Somedescription&AlphaProp=alpha