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

Source: Internet
Author: User

The first two articles introduce the implementation of modelvalidatoin server. if we set clientvalidationenabled to true in config, the client can also support form verification. what if this function is implemented? Today, let's take a look at the implementation of the model validation client.

I. modelclientvalidationrule class

This class defines how to output some client information:

    • Errormessage: gets or sets an error message for user-side verification rules.
    • Validationparameters:Retrieve verification parameter list.
    • Validationtype: gets or sets the verification type.
 1     Public   Class Modelclientvalidationrule {
2
3 Private Readonly Dictionary <String , Object > _ Validationparameters = New Dictionary < String , Object > ();
4 Private String _ Validationtype;
5
6 Public String Errormessage {
7 Get ;
8 Set ;
9 }
10
11 Public Idictionary < String , Object > Validationparameters {
12 Get {
13 Return _ Validationparameters;
14 }
15 }
16
17 Public String Validationtype {
18 Get {
19 Return _ Validationtype ?? String. empty;
20 }
21 Set {
22 _ Validationtype = value;
23 }
24 }
25 }

We know the data structure of this class. How is the data output? Let's take a look at the requiredattributeadapter class. Here we define a getclientvalidationrules method. This method returns the modelclientvalidationrequiredrule object (including the data that required validation needs to output to the client ).

 1    Public   Class Requiredattributeadapter: dataannotationsmodelvalidator <requiredattribute> {
2 Public Requiredattributeadapter (modelmetadata metadata, controllercontext context, requiredattribute attribute)
3 : Base (Metadata, context, attribute ){
4 }
5
6 Public Override Ienumerable <modelclientvalidationrule> getclientvalidationrules (){
7 Return New [] { New Modelclientvalidationrequiredrule (errormessage )};
8 }
9 }
2. If you want to get the custom client validaton information?

The above describes some system-built (required) Validation outputs. What if we need custom validation rules to output client data? We have introduced the custom verification in the dataannotationsmodelvalidatorprovider. getvalidators method, which is constructed through the defaultattributefactory delegate. Let's follow thisCodeTo continue with our thinking.

1Internal StaticDataannotationsmodelvalidationfactory defaultattributefactory =
2(Metadata, context, attribute) =>NewDataannotationsmodelvalidator (metadata, context, attribute );

Let me take a look at the implementation of the dataannotationsmodelvalidator. getclientvalidationrules method. We can see the following code line 4th, indicating that only the custom validationatriable interface can output client data.

 1     Public   Override Ienumerable <modelclientvalidationrule> getclientvalidationrules (){
2 Ienumerable <modelclientvalidationrule> Results =Base . Getclientvalidationrules ();
3
4 Iclientvalidatable clientvalidatable = attribute as iclientvalidatable;
5 If (Clientvalidatable! = Null ){
6 Results = results. Concat (clientvalidatable. getclientvalidationrules (metadata, controllercontext ));
7 }
8
9 Return Results;
10 }
3. If the User-Defined client validaton information is output to the browser?

The above analysis shows that we have obtained the cient validation data. How can we output the data to the browser?

Generally, the code on the view page is as follows:

1<DivClass="Editor-label">
2Name
3</Div>
4<DivClass="Editor-field">
5@ Html. textboxfor (M => M. username)
6@ Html. validationmessagefor (M => M. username)
7</Div>

That is to say, the client validaton information is output through the HTML. textboxfor method, so let's study how this method is implemented.

In the inputextension. CS component's inputhelper method, we found some code snippets related to client validaton. The getunobtrusivevalidationattributes method of the following 9th lines of code implements the output.

 1     //  If there are any errors for a named field, we add the CSS attribute.  
2 Modelstate;
3 If (Htmlhelper. viewdata. modelstate. trygetvalue (fullname, Out Modelstate )){
4 If (Modelstate. errors. Count>0 ){
5 Tagbuilder. addcssclass (htmlhelper. validationinputcssclassname );
6 }
7 }
8
9 Tagbuilder. mergeattributes (htmlhelper. getunobtrusivevalidationattributes (name, metadata ));

Source code of the getunobtrusivevalidationattributes method:

 1    // Only render attributes if unobtrusive client-side validation is enabled, and then only if we 've
2 // Never rendered validation for a field with this name in this form. Also, if there's no form context,
3 // Then we can't render the attributes (we 'd have no <form> to attach them ).
4 Public Idictionary < String , Object > Getunobtrusivevalidationattributes ( String Name, modelmetadata metadata ){
5 Dictionary < String , Object > Results = New Dictionary < String , Object > ();
6
7 // The ordering of these 3 checks (and the Early exits) is for performance reasons.
8 If (! Viewcontext. unobtrusivejavascriptenabled ){
9 Return Results;
10 }
11
12 Formcontext = viewcontext. getformcontextforclientvalidation ();
13 If (Formcontext = Null ){
14 Return Results;
15 }
16
17 String Fullname = viewdata. templateinfo. getfullhtmlfieldname (name );
18 If (Formcontext. renderedfield (fullname )){
19 Return Results;
20 }
21
22 Formcontext. renderedfield (fullname, True );
23
24 Ienumerable <modelclientvalidationrule> clientrules = clientvalidationrulefactory (name, metadata );
25 Bool Renderedrules = False ;
26
27 Foreach (Modelclientvalidationrule rule In Clientrules ){
28 Renderedrules = True ;
29 String Rulename = " Data-Val- " + Rule. validationtype;
30
31 Validateunobtrusivevalidationrule (rule, results, rulename );
32
33 Results. Add (rulename, httputility. htmlencode (rule. errormessage ?? String. Empty ));
34 Rulename + = " - " ;
35
36 Foreach ( VaR KVp In Rule. validationparameters ){
37 Results. Add (rulename + kVp. Key, kVp. value ?? String. Empty );
38 }
39 }
40
41 If (Renderedrules ){
42 Results. Add ( " Data-Val " , " True " );
43 }
44
45 Return Results;
46 }

Htmlhelper constructor source code:

 1     Public Htmlhelper (viewcontext, iviewdatacontainer viewdatacontainer, routecollection ){
2 If (Viewcontext = Null ){
3 Throw New Argumentnullexception ( " Viewcontext " );
4 }
5 If (Viewdatacontainer = Null ){
6 Throw New Argumentnullexception ( " Viewdatacontainer " );
7 }
8 If (Routecollection = Null ){
9 Throw New Argumentnullexception ( " Routecollection " );
10 }
11
12 Viewcontext = viewcontext;
13 Viewdatacontainer = viewdatacontainer;
14 Routecollection = routecollection;
15 Clientvalidationrulefactory = (name, metadata) => modelvalidatorproviders. providers. getvalidators (metadata ?? Modelmetadata. fromstringexpression (name, viewdata), viewcontext). selectiterator (V => v. getclientvalidationrules ());
16 }

Finally, we can see that within the getunobtrusivevalidationattributes method, MVC calls the clientvalidationrulefactory delegate to obtain the clientrules object. Its type is ienumerable <modelclientvalidationrule>, in this way, the client validation data marked on the model is output to the browser.

-------------------------------------- Feng Yi split line -------------------------------------------------

Through the above analysis, we know how the server outputs client validation data, so how does JavaScript verify it?

Next we will analyze the source code of jquery. Validate. unobtrusive. JS, which implements the client verification logic of MVC.

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

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

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.