Home > Backend Development > C#.Net Tutorial > Asp.net MVC method example of trimming the string input by the user

Asp.net MVC method example of trimming the string input by the user

零下一度
Release: 2017-06-19 09:58:28
Original
1795 people have browsed it

This article mainly introduces how Asp.net MVC trims all string fields entered by users. Friends in need can refer to

It is often necessary to trim the data entered by the user before inserting it into the data library or making a judgment. It is our general idea to process each ViewModel field separately. Recent investigations have revealed that it can actually be achieved in one go.

Implementation method in MVC4.6

1, implement the IModelBinder interface and 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();
    }
  }
Copy after login

2, add ModelBinder to the MVC binding library.

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);
    }
Copy after login

3, confirm the effect

Trim the space after the password and bind it When it comes to ViewModel, it becomes 1:

##Asp.net core 1.1 MVC implementation method

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);
    }
  }
Copy after login

2, add a custom Provider to 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;
    }
  }
Copy after login

3, add Provider to the binding Customize the management library


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

4, confirm the effect


Trim the space after the password and bind it When it comes to ViewModel, it becomes 1:


The above is the detailed content of Asp.net MVC method example of trimming the string input by the user. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template