How to change input before binding to model in asp.net mvc?
How can I intercept the submitted form input and modify it before it is attached to my model? For example, if I wanted to trim spaces from all text.
I tried to create a custom communication device like:
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 that doesn't sound like a challenge. Is there a better place to change the input value?
Note. I need to change the value before binding and validating it.
a source to share
Have you been careful to use your binder? For instance. The default linker can be replaced by doing this in Application_Start
:
ModelBinders.Binders.DefaultBinder = new MyVeryOwnModelBinder();
I have successfully done this multiple times by applying a reindex operation to a POST array.
I did re-indexing by overriding the method BindModel
by looking at the posted values ββin the dictionary bindingContext.ValueProvider
.
It should be possible to simply edit this dictionary to change the POST values ββprior to model binding.
a source to share