I want to write a modelbinder for ASP.NET MVC that will adjust the values that the user will see. Perhaps he will use the initial letter of the value, trim the lines, etc. Etc.
I would like to encapsulate this behavior in modelbinder.
For example, this is TrimModelBinderfor trimming 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 to the model, but when the page is re-rendered, the original values will be saved (because they are in the ModelState).
I would just like to re-display the trimmed values to the user.
There are many methods to override - for example, OnPropertyValidatedand OnPropertyValidatingetc.
, , .
Trim() - , . .