How can I modify input before model binding in asp.net mvc?

Posted by David G on Stack Overflow See other posts from Stack Overflow or by David G
Published on 2010-05-20T10:30:44Z Indexed on 2010/05/20 10:50 UTC
Read the original article Hit count: 269

Filed under:

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.

© Stack Overflow or respective owner

Related posts about asp.net-mvc