Reputation: 8562
I have some generic validation I want blanket applied to every string property on every model. I'm looking at subclassing the DefaultModelBinder
and adding logic by overridding the BindProperty
method. Would this be an appropriate thing to do?
Upvotes: 4
Views: 1102
Reputation: 8562
Subclassing the DefaultModelBinder
and overriding BindProperty
is working well for me. Calling the base.BindProperty ensures that the model's property is set, and I can then evaluate it for the global validation.
Upvotes: 1
Reputation: 60468
string
ModelState
public class MyCustomModelBinder : IModelBinder
{
public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
{
foreach (var propertyInfo in typeof(bindingContext.Model.GetType().GetProperties(BindingFlags.Public|BindingFlags.Instance))
{
if (propertyInfo.PropertyType == typeof(string))
{
var value = propertyInfo.GetValue(bindingContext.Model);
// validate
// append to ModelState if validation failed
bindingContext.ModelState.AddModelError(propertyInfo.Name, "Validation Failed");
}
}
}
}
public ActionResult MyActionMethod([ModelBinder(typeof(MyCustomModelBinder ))] ModelType model)
{
// ModelState.IsValid is false if validation fails
}
Upvotes: 2