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.

David Glenn
  • 24,412
  • 19
  • 74
  • 94

2 Answers2

1

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
  • 18,258
  • 2
  • 39
  • 63
  • 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 Glenn May 20 '10 at 10:57
  • 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 Glenn May 20 '10 at 11:21
0

Did you register the model binder in global.asax?

griegs
  • 22,624
  • 33
  • 128
  • 205
  • Yes, and if I override `BindModel` then I can see it is invoked through the debugger but not when I override `SetProperty` – David Glenn May 20 '10 at 10:55