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.
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: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
BindModelmethod, looking up posted values in thebindingContext.ValueProviderdictionary.It should be possible to just edit this dictionary in order to modify the POST’ed values before model binding.