How ASP. NET MVC does trim all user-entered string fields

Source: Internet
Author: User

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:

Summarize

It is so simple, for the future to do the memo.

How ASP. NET MVC does trim all user-entered string fields

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.