Andy
Andy

Reputation: 8562

MVC Model Binding - Validate EVERY property?

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

Answers (2)

Andy
Andy

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

dknaack
dknaack

Reputation: 60468

  1. Write your own custom modelbinder.
  2. Use Reflection to get all properties
  3. Check if the property is of type string
  4. Get the value of the property using reflection
  5. Run your custom validation and add validation errors to the ModelState

Sample

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");
           }
        }
    }
}

Use the ModelBinder

public ActionResult MyActionMethod([ModelBinder(typeof(MyCustomModelBinder ))] ModelType model)
{
  // ModelState.IsValid is false if validation fails
}

More Information

Upvotes: 2

Related Questions