MVC4.6中实现方式
1,实现IModelBinder接口,创建自定义ModelBinder。
public class TrimModelBinder : IModelBinder { public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext) { var valueResult = bindingContext.ValueProvider.GetValue(bindingContext.ModelName); string attemptedValue = valueResult?.AttemptedValue; return string.IsNullOrWhiteSpace(attemptedValue) ? attemptedValue : attemptedValue.Trim(); } } |
protected void Application_Start() { //System.Web.Mvc.ModelBinders.Binders.DefaultBinder = new ModelBinders.TrimModelBinder(); System.Web.Mvc.ModelBinders.Binders.Add(typeof(string), new ModelBinders.TrimModelBinder()); AreaRegistration.RegisterAllAreas(); FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); RouteConfig.RegisterRoutes(RouteTable.Routes); BundleConfig.RegisterBundles(BundleTable.Bundles); } |
将密码后面的空格做Trim处理,绑定到ViewModel的时候变成1了:
Asp.net core 1.1 MVC中实现方式
1,自定义ModelBinder并继承ComplexTypeModelBinder
public class TrimModelBinder : ComplexTypeModelBinder { public TrimModelBinder(IDictionary propertyBinders) : base(propertyBinders) { } protected override void SetProperty(ModelBindingContext bindingContext, string modelName, ModelMetadata propertyMetadata, ModelBindingResult result) { var value = result.Model as string; result= string.IsNullOrWhiteSpace(value) ? result : ModelBindingResult.Success(value.Trim()); base.SetProperty(bindingContext, modelName, propertyMetadata, result); } } |
public class TrimModelBinderProvider : IModelBinderProvider { public IModelBinder GetBinder(ModelBinderProviderContext context) { if (context.Metadata.IsComplexType && !context.Metadata.IsCollectionType) { var propertyBinders = new Dictionary(); for (int i = 0; i < context.Metadata.Properties.Count; i++) { var property = context.Metadata.Properties[i]; propertyBinders.Add(property, context.CreateBinder(property)); } return new TrimModelBinder(propertyBinders); } return null; } } |
services.AddMvc().AddMvcOptions(s => { s.ModelBinderProviders[s.ModelBinderProviders.TakeWhile(p => !(p is ComplexTypeModelBinderProvider)).Count()] = new TrimModelBinderProvider(); }); |
将密码后面的空格做Trim处理,绑定到ViewModel的时候变成1了:
总结
就是这么简单,为以后做备忘.