This article focuses on how ASP. NET MVC can be used to trim all user-entered string fields, as required by a friend
It is often necessary to trim the data entered by the user before inserting the database or judgment, and it is our general idea to handle each viewmodel field individually. Recent surveys have found that they can be implemented at once.
How to implement in MVC4.6
1, implement Imodelbinder interface, create 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 MVC's 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); }
3, confirm the effect
The space after the password is trim, bound to the ViewModel when it becomes 1:
How to implement ASP. NET Core 1.1 MVC
1, custom 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 provider to the binding management library
Services. Addmvc (). Addmvcoptions (s = = { s.modelbinderproviders[s.modelbinderproviders.takewhile (p =!) ( P is Complextypemodelbinderprovider)). Count ()] = new Trimmodelbinderprovider (); });
4, confirm the effect
The space after the password is trim, bound to the ViewModel when it becomes 1: