Created
April 23, 2012 07:50
-
-
Save fjeldstad/2469405 to your computer and use it in GitHub Desktop.
Simple "type-stamp" model binder that can bind complex, abstract objects provided they implement a specific interface ITypeStamped
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 TypeStampedModelBinder : DefaultModelBinder | |
{ | |
public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext) | |
{ | |
if (typeof(ITypeStamped).IsAssignableFrom(bindingContext.ModelType)) | |
{ | |
// Handle type-stamped model | |
var prefix = bindingContext.ModelName; | |
if (bindingContext.ValueProvider.ContainsPrefix(prefix)) | |
{ | |
var typeStamp = bindingContext.ValueProvider.GetValue(string.Format("{0}.{1}", prefix, "TypeStamp")); | |
var modelType = Type.GetType(typeStamp.AttemptedValue); | |
bindingContext.ModelMetadata = ModelMetadataProviders.Current.GetMetadataForType(null, modelType); | |
} | |
} | |
return base.BindModel(controllerContext, bindingContext); | |
} | |
} | |
public interface ITypeStamped | |
{ | |
string TypeStamp { get; } | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment