Asp.net MVC source code analysis-model validation (server side) implementation (1)

Source: Internet
Author: User
I. MVC validation usage:

In the Asp.net MVC framework, if you need to add verification to the model object, we can mark all attribute attributes inherited from validationattribute on the model attribute.

For exampleCode, Stringlength/range/compare are inherited from validationattribute class.

  Public   Class Logonmodel
{
[Required]
[Stringlength ( 10 )]
Public String Username { Get ; Set ;}

[Required]
[Range ( 5 , 10 )]
Public String Password { Get ; Set ;}

[Compare ( " Newpassword " , Errormessage = " The new password and confirmation password do not match. " )]
Public String Confirmpassword { Get ; Set ;}

[Display (name = " Remember me? " )]
Public Bool Rememberme { Get ; Set ;}
}

In the action, we can call the validatemodel method to verify the model object. If the verification fails, an invalidoperationexception is thrown, and the modelstate. isvalid status is false.

[Httppost]
Public Actionresult Logon (logonmodel model, String Returnurl)
{
This. validatemodel (model );
If (Modelstate. isvalid)
{
If (Membershipservice. validateuser (model. username, model. Password ))
{
Formsservice. signin (model. username, model. rememberme );
If (URL. islocalurl (returnurl ))
{
Return Redirect (returnurl );
}
Else
{
Return Redirecttoaction ( " Index " , " Home " );
}
}
Else
{
Modelstate. addmodelerror ( "" , " The user name or password provided is incorrect. " );
}
}

// If we got this far, something failed, redisplay form
Return View (model );
}

It should be noted that, if we do not call the model object on the validatemodel method action, it can also be verified by default, because MVC triggers the verification method in the defamodelmodelbinder. bindcomplexelementalmodel method in the object binding phase.

Defaultmodelbinder. CS

  Internal   Void Bindcomplexelementalmodel (controllercontext, modelbindingcontext bindingcontext, Object Model ){
// Need to replace the property filter + model object and create an inner binding context
Modelbindingcontext newbindingcontext = createcomplexelementalmodelbindingcontext (controllercontext, bindingcontext, model );

// Validation
If (Onmodelupdating (controllercontext, newbindingcontext )){
Bindproperties (controllercontext, newbindingcontext );
Onmodelupdated (controllercontext, newbindingcontext );
}
}
Protected Virtual Void Onmodelupdated (controllercontext, modelbindingcontext bindingcontext ){
Dictionary < String ,Bool > Startedvalid = New Dictionary < String , Bool > (Stringcomparer. ordinalignorecase );

Foreach (Modelvalidationresult validationresult In Modelvalidator. getmodelvalidator (Bindingcontext. modelmetadata, controllercontext). Validate ( Null )){
String Subpropertyname = createsubpropertyname (bindingcontext. modelname, validationresult. membername );

If (! Startedvalid. containskey (subpropertyname )){
Startedvalid [subpropertyname] = bindingcontext. modelstate. isvalidfield (subpropertyname );
}

If (Startedvalid [subpropertyname]) {
Bindingcontext. modelstate. addmodelerror (subpropertyname, validationresult. Message );
}
}
}
Ii. Source Code Analysis of validatemodel Method

Next, let's take a look at how MVC implements the validatemodel method verification.

 1    Protected   Internal  Void Validatemodel ( Object Model ){
2 Validatemodel (model, Null /* Prefix */ );
3 }
4
5 Protected Internal Void Validatemodel (Object Model, String Prefix ){
6 If (! Tryvalidatemodel (model, prefix )){
7 Throw New Invalidoperationexception (
8 String. Format (
9 Cultureinfo. currentculture,
10 Mvcresources. controller_validate_validationfailed,
11 Model. GetType (). fullname
12 )
13 );
14 }
15 }
16
17 Protected Internal Bool Tryvalidatemodel ( Object Model ){
18 Return Tryvalidatemodel (model, Null /* Prefix */ );
19 }
20
21 Protected Internal Bool Tryvalidatemodel ( Object Model, String Prefix ){
22 If (Model = Null ){
23 Throw New Argumentnullexception ( " Model " );
24 }
25
26 Modelmetadata metadata = modelmetadataproviders. Current. getmetadatafortype () => model, model. GetType ());
27
28 Foreach (Modelvalidationresult validationresult In Modelvalidator. getmodelvalidator (Metadata, controllercontext). Validate ( Null )){
29 Modelstate. addmodelerror (defaultmodelbinder. createsubpropertyname (prefix, validationresult. membername), validationresult. Message );
30 }
31
32 Return Modelstate. isvalid;
33 }

We can see that row 3 MVC calls modelvalidator. getmodelvalidator to obtain the model's validator object. Let's take a look at the implementation of this method, and it returns the compositemodelvalidator object.

 
Public StaticModelvalidator getmodelvalidator (modelmetadata metadata, controllercontext context ){
Return NewCompositemodelvalidator (metadata, context );
}
 
Compositemodelvalidator. CS
 1    Private   Class Compositemodelvalidator: modelvalidator {
2 Public Compositemodelvalidator (modelmetadata metadata, controllercontext)
3 : Base (Metadata, controllercontext ){
4 }
5
6 Public Override Ienumerable <modelvalidationresult> validate ( Object Container ){
7 Bool Propertiesvalid = True ;
8
9 Foreach (Modelmetadata propertymetadata In Metadata. properties ){
10 Foreach (Modelvalidator propertyvalidator In Propertymetadata. getvalidators (Controllercontext )){
11 // Robbin: If modelvalidationresult is returned for validate, the verification fails.
12 Foreach (Modelvalidationresult propertyresult In Propertyvalidator. Validate (Metadata. Model )){
13 Propertiesvalid = False ;
14 Yield Return New Modelvalidationresult {
15 Membername = defamodelmodelbinder. createsubpropertyname (propertymetadata. propertyname, propertyresult. membername ),
16 Message = propertyresult. Message
17 };
18 }
19 }
20 }
21
22 If (Propertiesvalid ){
23 Foreach (Modelvalidator typevalidator In Metadata. getvalidators (controllercontext )){
24 Foreach (Modelvalidationresult typeresult In Typevalidator. Validate (container )){
25 Yield Return Typeresult;
26 }
27 }
28 }
29 }
30 }
 
Let's take a look at the implementation of the method propertymetadata. getvalidators in the above 10th rows. It returns all validator implementations. In addition, in 12 rows, the validate method of these implementations is called for verification.
 
Public VirtualIenumerable <modelvalidator> getvalidators (controllercontext context ){
ReturnModelvalidatorproviders. providers. getvalidators (This, Context );
}

it calls the getvalidators method of the modelvalidatorproviders. Providers object. The object type is modelvalidatorprovidercollection. Next let's take a look at the implementation of modelvalidatorproviders. Providers

  Public   static   class  modelvalidatorproviders {
private static readonly modelvalidatorprovidercollection _ providers = New modelvalidatorprovidercollection () {
New dataannotationsmodelvalidatorprovider (),
New dataerrorinfomodelvalidatorprovider (),
New clientdatatypemodelvalidatorprovider ()
};
Public static modelvalidatorprovidercollection providers {
Get {< br> return _ providers;
}< BR >}< br>
}

This object contains three validatorproviders by default during initialization. here we need to pay attention to dataannotationsmodelvalidatorprovider, which provides all the default system validation rules (except remoteattribute ).

Next, we will analyze in detail the implementation of dataannotationsmodelvalidatorprovider and the design pattern used.

 

Reprinted please indicate the source: http://www.cnblogs.com/RobbinHan/archive/2011/12/15/2289228.html 

Author: November rain http://www.cnblogs.com/RobbinHan

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.