Last active
August 29, 2015 14:17
-
-
Save raducugheorghe/eebf4068ef5d10eb4f0e to your computer and use it in GitHub Desktop.
[C#][MVC] Abstract factory model binder
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class AbstractFactoryModelBinder : DefaultModelBinder | |
{ | |
public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext) | |
{ | |
var modelType = bindingContext.ModelType; | |
if (modelType.IsAbstract) | |
{ | |
var value = bindingContext.ModelName == "model" ? bindingContext.ValueProvider.GetValue("Type") : bindingContext.ValueProvider.GetValue(bindingContext.ModelName + ".Type"); | |
if (value == null) | |
throw new ApplicationException("View does not contain Type"); | |
var factoryMethod = modelType.GetMethod("CreateFor"); | |
if (factoryMethod == null) | |
{ | |
throw new ApplicationException("Abstract factory must have static CreateFor (String type) method!"); | |
} | |
var model = factoryMethod.Invoke(null, new object[]{value.AttemptedValue}); | |
var instance = bindingContext.Model ?? base.CreateModel(controllerContext, bindingContext, model.GetType()); | |
bindingContext.ModelMetadata = ModelMetadataProviders.Current.GetMetadataForType(() => instance, model.GetType()); | |
} | |
return base.BindModel(controllerContext, bindingContext); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment