![]() Then this in your MVC application/library: /// Public class StringTrimAttribute : Attribute / option to control what happens to empty strings. / When that is required you must additionally use the / This attribute does not imply that empty strings should be converted to null. ![]() / Data Annotations provides no mechanism to coerce the value. / Support for trimming is implmented in the model binder, as currently / Denotes a data field that should be trimmed during binding, removing any spaces. Put this in your entity/shared library: /// TryUpdateModel(model) to apply and ModelState.Clear() to accept all changes. UnvalidatedValueProvider.GetValue(bindingContext.ModelName, !shouldPerformRequestValidation) Īnother variant of answer but with a different twist:ġ) I prefer the opt-in "StringTrim" attribute mechanism (rather than the opt-out "NoTrim" example of An additional call to SetModelValue is required to ensure the ModelState is populated correctly and the default validation/accept/reject pattern can be used as normal, i.e. Var value = unvalidatedValueProvider = null ?ī(bindingContext.ModelName) : Var unvalidatedValueProvider = bindingContext.ValueProvider as IUnvalidatedValueProvider Var shouldPerformRequestValidation = & My original answer was reduced to deal just with the question the OP had posed, but for those who are interested, you can deal with validation by using the following extended model binder: public class TrimStringModelBinder : IModelBinder However, if you override the default model binder as other answers here suggest, that will only work when binding properties on models, not when you have a string as an argument to an action methodĮdit: a commenter asked about dealing with the situation when a field should not be validated. I find it is better to use a model binder like this, rather than overriding the default model binder, because then it will be used whenever you are binding a string, whether that's directly as a method argument or as a property on a model class. You need to include this line somewhere in Application_Start() in your file to use the model binder when binding strings: (typeof(string), new TrimStringModelBinder()) Return string.IsNullOrWhiteSpace(attemptedValue) ? attemptedValue : attemptedValue.Trim() Var attemptedValue = value?.AttemptedValue Public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext) With improvements in C# 6, you can now write a very compact model binder that will trim all string inputs: public class TrimStringModelBinder : IModelBinder
0 Comments
Leave a Reply. |