經常需要對用戶輸入的數據在插入數據庫或者判斷之前做Trim處理,針對每個ViewModel的字段各自做處理是我們一般的想法。最近調查發現其實也可以一次性實現的。
MVC4.6中實現方式
1,實現IModelBinder接口,創建自定義ModelBinder。
1
2
3
4
5
6
7
8
9
10
|
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(); } } |
2,添加ModelBinder到MVC的綁定庫。
1
2
3
4
5
6
7
8
9
|
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); } |
3,確認一下效果
將密碼后面的空格做Trim處理,綁定到ViewModel的時候變成1了:
Asp.net core 1.1 MVC中實現方式
1,自定義ModelBinder并繼承ComplexTypeModelBinder
1
2
3
4
5
6
7
8
9
10
11
12
13
|
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); } } |
2,為ModelBinder添加自定義Provider
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
|
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 ; } } |
3,將Provider添加到綁定管理庫
1
2
3
4
|
services.AddMvc().AddMvcOptions(s => { s.ModelBinderProviders[s.ModelBinderProviders.TakeWhile(p => !(p is ComplexTypeModelBinderProvider)).Count()] = new TrimModelBinderProvider(); }); |
4,確認一下效果
將密碼后面的空格做Trim處理,綁定到ViewModel的時候變成1了:
以上所述是小編給大家介紹的Asp.net MVC 對所有用戶輸入的字符串字段做Trim處理的方法,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復大家的。在此也非常感謝大家對服務器之家網站的支持!
原文鏈接:http://www.cnblogs.com/lixiaobin/p/AspnetMVCTrim.html