How to use MVC parameters to validate a model after C # MVC enters the action method

Source: Internet
Author: User

This problem has plagued me for a long time after the Action received a JSON string and then serialized the string as an entity, and then how to use MVC's own parameter Validation framework to validate the parameters. Some people may say that when invoking an interface, add a request header, set Contentype to Application/json, and the action method can accept JSON parameters with the entity. But that's not the situation I'm dealing with. All I need to do is accept the JSON string and serialize it to the entity. Do not for me why, I was so stubborn. Ha ha

Solution directly on the code, by adding an extension method to the controller to meet my needs, one thing to note is that when the controller calls the extension method, it is necessary to use this.xxx. Okay, on the code.

Extension methods:

usingSystem;usingSystem.Collections;usingSystem.Linq.Expressions;usingSYSTEM.WEB.MVC;namespacelyt.framework{ Public Static Partial classcontrollerextensions { Public Static BOOLValidatemodelextensions ( ThisController controller,Objectmodel) {            returnValidatemodelextensions (Controller, model,NULL); }        Private Static BOOLValidatemodelextensions ( ThisController controller,ObjectModelstringprefix =NULL)         {            if(model = =NULL)            {                Throw NewArgumentNullException ("Model"); }            if(model isIEnumerable) {                foreach(varIteminchModel asIEnumerable)                {validatemodelbase (Controller, item, prefix); }            }            Else{validatemodelbase (Controller, model, prefix); }            returnController.        Modelstate.isvalid; }        Private Static voidValidatemodelbase (Controller controller,ObjectModelstringprefix) {Modelmetadata metadata= ModelMetadataProviders.Current.GetMetadataForType (() =model, model.            GetType ()); foreach(Modelvalidationresult ValidationresultinchModelvalidator.getmodelvalidator (metadata, controller. ControllerContext). Validate (NULL) ) {controller.            Modelstate.addmodelerror (createsubpropertyname (prefix, validationresult.membername), validationresult.message); }        }        Private Static stringCreatesubpropertyname (stringPrefixstringPropertyName) {            if(string.isnullorempty (prefix)) {returnPropertyName; }            Else if(String.IsNullOrEmpty (PropertyName)) {returnprefix; }            Else            {                returnPrefix +"."+PropertyName; }        }    }}
View Code

Invocation Example:

 PublicActionResult Validatemodeltest (stringJsonmodel) {List<PersonModel> list = jsonconvert.deserializeobject<list<personmodel>>(Jsonmodel); if( This. Validatemodelextensions (list)) {returnContent ("OK"); }            Else            {                returnContent ("parameter Exception"); }        }
View Code

Get.

Now you can use it to achieve a variety of business needs.

How to use MVC parameters to validate a model after C # MVC enters the action method

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.