tags:

views:

40

answers:

2

How can I intercept submitted form input and modify it before it is bound to my model? For example, if I wanted to trim the whitespace from all text.

I have tried creating a custom model binder like so:

public class CustomBinder : DefaultModelBinder {

  protected override void SetProperty(ControllerContext controllerContext, ModelBindingContext bindingContext, PropertyDescriptor propertyDescriptor, object value) {
    string newValue = ((string)value).Trim(); //example code to create new value but could be anything
    base.SetProperty(controllerContext, bindingContext, propertyDescriptor, newValue);
  }

}

but this doesn't seem to be invoked. Is there a better place to modify the input value?

Note: I need to modify the value before it is bound and validated.

A: 

Did you register the model binder in global.asax?

griegs
Yes, and if I override `BindModel` then I can see it is invoked through the debugger but not when I override `SetProperty`
David G
+1  A: 

Did you make sure that your model binder was used? E.g. the default model binder can be replaced by doing this in Application_Start:

ModelBinders.Binders.DefaultBinder = new MyVeryOwnModelBinder();

I have successfully done this multiple times, applying a re-indexing operation to a POST'ed array.

I did the re-indexing by overriding the BindModel method, looking up posted values in the bindingContext.ValueProvider dictionary.

It should be possible to just edit this dictionary in order to modify the POST'ed values before model binding.

mookid8000
If I override `BindModel` then I can see my CustomBinder is being invoked through the debugger but when I just override `GetProperty` it isn't.
David G
Arghhh! I was registering my model binder against the property type using `ModelBinders.Binders.Add()` and not as the default model binder. Using `ModelBinders.Binders.DefaultBinder = new CustomBinder();` invokes `SetPoperty` as expected.
David G