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.

+2


a source to share


2 answers


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.

+1


a source


Have you registered your model binding in global.asax?



0


a source







All Articles