您好,登錄后才能下訂單哦!
這篇文章將為大家詳細(xì)講解有關(guān)Asp.net MVC如何對(duì)輸入的字符串字段做Trim處理,小編覺得挺實(shí)用的,因此分享給大家做個(gè)參考,希望大家閱讀完這篇文章后可以有所收獲。
MVC4.6中實(shí)現(xiàn)方式
1,實(shí)現(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的綁定庫(kù)。
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,確認(rèn)一下效果
將密碼后面的空格做Trim處理,綁定到ViewModel的時(shí)候變成1了:
Asp.net core 1.1 MVC中實(shí)現(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添加到綁定管理庫(kù)
services.AddMvc().AddMvcOptions(s => { s.ModelBinderProviders[s.ModelBinderProviders.TakeWhile(p => !(p is ComplexTypeModelBinderProvider)).Count()] = new TrimModelBinderProvider(); });
4,確認(rèn)一下效果
將密碼后面的空格做Trim處理,綁定到ViewModel的時(shí)候變成1了:
關(guān)于“Asp.net MVC如何對(duì)輸入的字符串字段做Trim處理”這篇文章就分享到這里了,希望以上內(nèi)容可以對(duì)大家有一定的幫助,使各位可以學(xué)到更多知識(shí),如果覺得文章不錯(cuò),請(qǐng)把它分享出去讓更多的人看到。
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。