Asp.net MVC performs Trim processing on string fields input by all users. mvctrim

Source: Internet
Author: User

Asp.net MVC performs Trim processing on string fields input by all users. mvctrim

We often need to Trim the user input data before it is inserted into the database or judgment. It is our general idea to process each ViewModel field separately. Recent surveys have found that this can also be implemented at one time.

Implementation Method in MVC4.6

1. Implement the IModelBinder interface to create a custom 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. Add ModelBinder to the binding library of 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. Check the effect.

Trim the space behind the password, and 1 is changed when it is bound to ViewModel:

Implementation in Asp.net core 1.1 MVC

1. Customize ModelBinder and inherit 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. Add a custom Provider for ModelBinder

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. Add the Provider to the bound management library.

services.AddMvc().AddMvcOptions(s =>      {        s.ModelBinderProviders[s.ModelBinderProviders.TakeWhile(p => !(p is ComplexTypeModelBinderProvider)).Count()] = new TrimModelBinderProvider();      });

4. Check the effect.

Trim the space behind the password, and 1 is changed when it is bound to ViewModel:

The above section describes how Asp.net MVC performs Trim processing on string fields entered by all users. If you have any questions, please leave a message, the editor will reply to you in a timely manner. Thank you very much for your support for the help House website!

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.