I’m trying to build a generic model binder that uses reflection to assign properties to a specified type of object retrieved from the BindingContext. So something like this:
public class ModelBinder : IModelBinder
{
public object BindModel<T, K> (ControllerContext controllerContext, ModelBindingContext bindingContext)
where T : class, new()
where K : class
{
Type ObjectType = typeof(T);
Type InterfaceType = typeof(K);
T obj = new T();
foreach (var Property in ObjectType.GetProperties(BindingFlags.DeclaredOnly | BindingFlags.Public | BindingFlags.Instance))
{
Type PropertyType = Property.PropertyType;
// checks if property is a custom data object
if (!(PropertyType.GetGenericArguments().Count() > 0 && PropertyType.GetGenericArguments()[0].GetInterfaces().Contains(InterfaceType)))
{
Property.SetValue(obj, bindingContext.ValueProvider.GetValue(Property.Name), null);
}
}
return obj;
}
Obviously this doesn’t work as it isn’t correctly implementing the IModelBinder interface. Is something like this possible?
Edit:
To expand on why I am doing this, our objects use a lot of different custom objects. For instance, the Class object:
public class Class : ModelBase<Class>
{
public Class () { }
public virtual string ClassDescription { get; set; }
public virtual string ClassName { get; set; }
public virtual LookUp ClassType { get; set; }
public virtual double Credits { get; set; }
public virtual bool Documents { get; set; }
public virtual LookUp PracticeArea { get; set; }
}
uses the LookUp class:
public class LookUp : ModelBase<LookUp>
{
public LookUp () { }
public virtual string DisplayName { get; set; }
public virtual LookUpType Type { get; set; }
}
dropdowns are used for LookUps and other objects so my custom model binder for Class/Create would do something like:
LookUp ClassType = LookUp.Load(long.Parse(bindingContext.ValueProvider.GetValue("ClassType").AttemptedValue))
I don’t see how something like this can be dealt with using the DefaultModelBinder.
So I’ve come up with a working (for now) solution. It’s not very generic at the moment but it works for my purposes.