小編給大家分享一下Asp.net MVC如何對所有用戶輸入的字符串字段做Trim處理,相信大部分人都還不怎么了解,因此分享這篇文章給大家參考一下,希望大家閱讀完這篇文章后大有收獲,下面讓我們一起去了解一下吧!
MVC4.6中實現(xiàn)方式
1,實現(xiàn)IModelBinder接口,創(chuàng)建自定義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(); } }
2,添加ModelBinder到MVC的綁定庫。
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中實現(xiàn)方式
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); } }
2,為ModelBinder添加自定義Provider
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添加到綁定管理庫
services.AddMvc().AddMvcOptions(s => { s.ModelBinderProviders[s.ModelBinderProviders.TakeWhile(p => !(p is ComplexTypeModelBinderProvider)).Count()] = new TrimModelBinderProvider(); });
4,確認一下效果
將密碼后面的空格做Trim處理,綁定到ViewModel的時候變成1了:
以上是“Asp.net MVC如何對所有用戶輸入的字符串字段做Trim處理”這篇文章的所有內(nèi)容,感謝各位的閱讀!相信大家都有了一定的了解,希望分享的內(nèi)容對大家有所幫助,如果還想學(xué)習(xí)更多知識,歡迎關(guān)注創(chuàng)新互聯(lián)行業(yè)資訊頻道!
網(wǎng)頁標題:Asp.netMVC如何對所有用戶輸入的字符串字段做Trim處理-創(chuàng)新互聯(lián)
本文網(wǎng)址:http://www.rwnh.cn/article34/joepe.html
成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供網(wǎng)站制作、App設(shè)計、商城網(wǎng)站、網(wǎng)站收錄、網(wǎng)站導(dǎo)航、網(wǎng)站維護
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時需注明來源: 創(chuàng)新互聯(lián)
猜你還喜歡下面的內(nèi)容