I\'ve been running some experiments with ASP.NET MVC2 and have run into an interesting problem.
I\'d like to define an interface around the objects that will be used
After inspecting the source for System.Web.MVC.DefaultModelBinder, it looks like this can be solved using a slightly different approach. If we rely more heavily on the base implementation of BindModel, it looks like we can construct a PhotoImpl object while still pulling the validation attributes from IPhoto.
Something like:
public class PhotoModelBinder : DefaultModelBinder
{
public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
{
if (bindingContext.ModelType == typeof(IPhoto))
{
ModelBindingContext newBindingContext = new ModelBindingContext()
{
ModelMetadata = ModelMetadataProviders.Current.GetMetadataForType(
() => new PhotoImpl(), // construct a PhotoImpl object,
typeof(IPhoto) // using the IPhoto metadata
),
ModelState = bindingContext.ModelState,
ValueProvider = bindingContext.ValueProvider
};
// call the default model binder this new binding context
return base.BindModel(controllerContext, newBindingContext);
}
else
{
return base.BindModel(controllerContext, bindingContext);
}
}
}