I want to write a modelbinder for ASP.NET MVC that will correct values that will be visible to the user. Maybe it will capitalize the initial letter of a value, trim strings, etc. etc.
I'd like to encapsulate this behavior within a modelbinder.
For instance here is a TrimModelBinder
to trim strings. (taken from here)
public class TrimModelBinder : DefaultModelBinder
{
protected override void SetProperty(ControllerContext controllerContext,
ModelBindingContext bindingContext,
System.ComponentModel.PropertyDescriptor propertyDescriptor, object value)
{
if (propertyDescriptor.PropertyType == typeof(string))
{
var stringValue = (string)value;
if (!string.IsNullOrEmpty(stringValue))
stringValue = stringValue.Trim();
value = stringValue;
}
base.SetProperty(controllerContext, bindingContext,
propertyDescriptor, value);
}
}
This will set the values into the model, but when the page is redisplayed the original values will persist (because they're in ModelState).
I'd like to just re-display the trimmed values to the user.
Theres a whole lot of methods to override - like OnPropertyValidated
, and OnPropertyValidating
etc.
I could probably get it to work, but I don't want to have some unintended side effect if I override the wrong method.
I'd rather not try to do a Trim() or whatever the logic is when I'm generating the view. I want to encapsulate this logic completely within a modelbinder.