Skip to content

Instantly share code, notes, and snippets.

@mhwelander
Created June 10, 2014 09:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mhwelander/cc6d25bb5cbb5afc4394 to your computer and use it in GitHub Desktop.
Save mhwelander/cc6d25bb5cbb5afc4394 to your computer and use it in GitHub Desktop.
namespace TC.ServicesPortal.ModelBinders
{
public class InterfaceModelBinder : DefaultModelBinder
{
protected override object CreateModel(ControllerContext controllerContext, ModelBindingContext bindingContext, Type modelType)
{
var type = bindingContext.ModelType;
if (type.IsInterface)
{
var fieldTypeKey = bindingContext.ModelName + ".FieldType";
var assemblyFieldTypeKey = bindingContext.ModelName + ".FieldTypeAssembly";
if (!String.IsNullOrEmpty(fieldTypeKey))
{
var fieldType = ((string[])bindingContext.ValueProvider.GetValue(fieldTypeKey).RawValue)[0];
var assemblyFieldType = ((string[])bindingContext.ValueProvider.GetValue(assemblyFieldTypeKey).RawValue)[0];
modelType = Type.GetType(fieldType + ", " + assemblyFieldType);
var instance = Activator.CreateInstance(modelType);
bindingContext.ModelMetadata = ModelMetadataProviders.Current.GetMetadataForType(() => instance, modelType);
return instance;
}
}
return null;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment