Skip to content

Instantly share code, notes, and snippets.

@fjeldstad
Created April 23, 2012 07:50
Show Gist options
  • Save fjeldstad/2469405 to your computer and use it in GitHub Desktop.
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
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