使用ModelBinder自动过滤获取Model值的空格

  1. 类的定义
     public class MyModelBinder : DefaultModelBinder
        {
            protected override void SetProperty(ControllerContext controllerContext,
              ModelBindingContext bindingContext,
              System.ComponentModel.PropertyDescriptor propertyDescriptor, object value)
            {
    
                trim(propertyDescriptor, ref value);
    
    
                base.SetProperty(controllerContext, bindingContext,
                                    propertyDescriptor, value);
            }
    
    
            private void trim(System.ComponentModel.PropertyDescriptor propertyDescriptor, ref object value)
            {
                if (propertyDescriptor.PropertyType == typeof(string))
                {
                    var stringValue = (string)value;
                    if (!string.IsNullOrWhiteSpace(stringValue))
                    {
                        stringValue = stringValue.Trim();
                    }
    
                    value = stringValue;
                }
            }
    
        }
  2. 类的调用
    在Global.asax的Application_Start添加代码:ModelBinders.Binders.DefaultBinder = new MyModelBinder();
原文地址:https://www.cnblogs.com/gossip/p/2521632.html