Search code examples
asp.net-mvcasp.net-mvc-validationasp.net-mvc-filters

How to get model after binding but before validation?


Is it possible to make a global interception for a model just after it is created in binder but before it is validating. I tried filters, but filter is invoked after validation.


Solution

  • Something like this should work:

    public class CustomModelBinder: DefaultModelBinder
    {
        protected override void OnModelUpdated(ControllerContext controllerContext, ModelBindingContext bindingContext)
        {
            base.OnModelUpdated(controllerContext, bindingContext);
            //You now have access to "bindingContext.Model" which is your model.
        }
    }
    

    And then in Application_Start in Globals.asax (don't forget this part):

    ModelBinders.Binders.DefaultBinder = new CustomModelBinder();