Click here to Skip to main content
15,907,001 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Any shortcut for trim all value in MVC controller.

What I have tried:

NO. currently, all fields are using a trim.
Posted
Updated 3-May-18 3:56am

1 solution

Make one class

public class TrimModelBinder : System.Web.Mvc.DefaultModelBinder
   {
       protected override void SetProperty(ControllerContext controllerContext, System.Web.Mvc.ModelBindingContext bindingContext,System.ComponentModel.PropertyDescriptor propertyDescriptor, object value)
       {
           if (propertyDescriptor.PropertyType == typeof(string))
           {
               var stringValue = (string)value;
               if (!string.IsNullOrWhiteSpace(stringValue))
               {
                   value = stringValue.Trim();
               }
               else
               {
                   value = null;
               }
           }
           base.SetProperty(controllerContext, bindingContext,
                               propertyDescriptor, value);
       }
   }


//global.asax Application_Start event.

ModelBinders.Binders.DefaultBinder = new TrimModelBinder();



asp.net - Best way to trim strings after data entry. Should I create a custom model binder? - Stack Overflow[^]
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900