欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Asp.net MVC 對所有用戶輸入的字符串字段做Trim處理的方法

 更新時間:2017年06月17日 15:32:07   作者:云中客  
這篇文章主要介紹了Asp.net MVC 如何對所有用戶輸入的字符串字段做Trim處理,需要的朋友可以參考下

經(jīng)常需要對用戶輸入的數(shù)據(jù)在插入數(shù)據(jù)庫或者判斷之前做Trim處理,針對每個ViewModel的字段各自做處理是我們一般的想法。最近調(diào)查發(fā)現(xiàn)其實也可以一次性實現(xiàn)的。

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處理的方法,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復大家的。在此也非常感謝大家對腳本之家網(wǎng)站的支持!

相關文章

最新評論