. Net 3.0 Adds a syntax sugar is the extension method, in fact, the extension method is the essence of the static method of the class call, although the extension method only changes the way we write code, but if we use properly, can give us a huge increase in coding efficiency. For the use of C # extension methods, I do not elaborate, the patch code to illustrate the use of extension methods, we will recall.
Copy Code code as follows:
public static Class Extensions
{
public static string Endwith (this string str)
{
return str + "@";
}
}
For this very simple piece of code, I'm sure you'll understand that you can see that the extension method is used to define a static method in a static class that adds this to the method parameter.
Then it's much simpler to use the extension method. The following code fragment is the extension method for string extensions that will appear on the page @
Copy Code code as follows:
String str = "";
Response.Write (str. Endwith ());
Extension method is not the focus of this topic, the focus of this topic is to explain how to use the extension method to link the MVC 3 of the page validation. For the validation of MVC, there are many ways, which we often use is model validation, this is the most direct and efficient way we operate, can be a field of multiple conditions to verify. However, there is a disadvantage of this validation, that we can not see directly on the page of the validation of the field, unless we go to the model layer to view, but usually a project is a project team, we are not necessarily responsible for the development of the model layer, so this will encounter a communication problem. As we all know, the communication costs of programmers are very high.
Now provides another way to do page validation, which can also validate multiple conditions for a page element, and it is done on the client. To use this validation, we must understand a jquery plug-in, that is the Jquery.validation.js file, this is the element to verify the JS file.
There is a point of knowledge that we must understand. Which class is directly inherited from the razor view of MVC 3? I believe many friends will not hesitate to say is viewpage, of course, this can not be said to be wrong, because MVC 2 is indeed inherited from the ViewPage base class, but in Razor view, is inherited from the Webviewpage class, if your extension method extends ViewPage, So sorry, you can't see this extension method on the page unless you inherit from Webviewpage. I hope you expand the page method to pay attention to the inheritance of the class.
said the preparation work, then we cut to the point, first paste out the code, and then we gradually analysis.
Copy Code code as follows:
Namespace Mvcweb.extensions
{
public class Jqueryhelper
{
Public ViewContext ViewContext {get; private set;}
Public webviewpage ViewPage {get; private set;}
Public routecollection routecollection {get; private set;}
Public Jqueryhelper (ViewContext viewcontext, Webviewpage page, RouteCollection routecollection)
{
This. ViewContext = ViewContext;
This. ViewPage = page;
This. RouteCollection = routecollection;
}
Public Jqueryhelper (ViewContext viewcontext, Webviewpage viewpage): This (ViewContext, ViewPage, routetable.routes) {}
}
public static Class Jqueryextensions
{
public static Jqueryhelper Jquery (this webviewpage page)
{
var key = typeof (Jqueryhelper);
var jquery = page. Pagedata[key] as Jqueryhelper;
if (jquery = null)
{
Page. Pagedata[key] = jquery = new Jqueryhelper (page. ViewContext, page);
}
return jquery;
}
}
public class Jqueryvalidations
{
Public webviewpage Page {get; private set;}
Public jqueryvalidations (Webviewpage page)
{
This. page = page;
}
Private dictionary<string, dictionary<string, object>> m_rules = new dictionary<string, Dictionary< String, object>> ();
Private dictionary<string, dictionary<string, object>> m_message = new dictionary<string, Dictionary <string, object>> ();
public void Required (string name,string message)
{
This. Addruleandmessage (name, "required", true, message);
}
public void e-mail (string name, String message)
{
This. Addruleandmessage (name, "email", true,message);
}
public void number (string name, String message)
{
This. Addruleandmessage (Name, "number", true, message);
}
public void Range (string name,int min,int max, string message)
{
This. Addruleandmessage (name, range, new int[] {min, max}, message);
}
public string toscripts (string form)
{
JavaScriptSerializer serializer = new JavaScriptSerializer ();
StringBuilder builder = new StringBuilder ();
Builder. Append ("$ (");
Serializer. Serialize (form, builder);
Builder. Append ("). Validate (");
Serializer. Serialize (
New
{
Rules = This.m_rules,
Messages = This.m_message,
OnKeyUp = False
}, builder);
Builder. Append (");");
Return builder. ToString ();
}
Public validationelement Element (string name)
{
Return to new Validationelement (name, this);
}
private void Addruleandmessage (string name, string rule, object value, String message)
{
if (!this.m_rules. ContainsKey (name))
{
This.m_rules[name] = new dictionary<string, object> ();
}
This.m_rules[name][rule] = value;
if (!string. IsNullOrEmpty (message))
{
if (!this.m_message. ContainsKey (name))
{
This.m_message[name] = new dictionary<string, object> ();
}
This.m_message[name][rule] = message;
}
}
}
public class Validationelement
{
Public validationelement (string name, jqueryvalidations validations)
{
This. name = name;
This. validations = validations;
}
public string Name {get; private set;}
Public jqueryvalidations validations {get; private set;}
Public validationelement Required (String message)
{
This. Validations.required (this. Name, message);
return this;
}
Public validationelement E-mail (string message)
{
This. Validations.email (this. Name, message);
return this;
}
Public validationelement Number (string message)
{
This. Validations.number (this. Name, message);
return this;
}
Public validationelement Range (int min, int max, string message)
{
This. Validations.range (this. Name, Min, max, message);
return this;
}
}
public static Class Jqueryvalidationextensions
{
public static jqueryvalidations validations (this jqueryhelper jquery)
{
Return jquery. Validations ("(default)");
}
public static jqueryvalidations validations (this jqueryhelper jquery, string name)
{
var key = typeof (Jqueryvalidations) + "+" + name;
var page = jquery. ViewPage;
var validations = page. Pagedata[key] as jqueryvalidations;
if (validations = null)
{
Page. Pagedata[key] = validations = new Jqueryvalidations (page);
}
return validations;
}
}
}
In this code defines the Jqueryhelper class, is the extension of Webviewpage, which has a method toscript we should pay special attention to this method is to display a piece of JS on the page, That is, Jquery.validation.js will be used to verify the page elements of JS.
The specific code I will not elaborate, I introduce the basic idea bar. First we define a Jqueryhelper class and then top a jqueryvalidation class to define the validation that can be made to the page element. There is a chain method that must be used for each validation method to return the result is the object of the Jqueryvalidation class, so that we can do chain operation.
The dictionary is used to store the validated tag Name property values, error messages, and validation rules, and in the end, the toscript can be pieced together in a JS to be submitted.
Well, if you look at the results, you'll know more about the purpose of this chain approach.
Copy Code code as follows:
@{
Layout = null;
}
@using mvcweb.extensions
<! DOCTYPE html>
<title>Index</title>
<script src= "Http://www.cnblogs.com/Scripts/jquery-1.5.1.js" type= "Text/javascript" ></script>
<script type= "Text/javascript" src= "@Url. Content (" Http://www.cnblogs.com/Scripts/jquery-1.5.1-vsdoc.js ") > </script>
<script type= "Text/javascript" src= "@Url. Content (" Http://www.cnblogs.com/scripts/jquery.validate.js ") > </script>
<body>
<div>
<form id= "form" action= "" method= "POST" >
<input type= "text" id= "user. Name "name=" user. Name "/>
@{this. Jquery (). Validations (). Required ("user.") Name "," User name is required pro ");}
<select name= "user. Gender ">
<option value= "" >please select...</option>
<option value= "1" >Male</option>
<option value= "2" >Femle</option>
</select>
@{this. Jquery (). Validations (). Required ("user.") Gender ", null);}
<input type= "text" name= "user. Email "/>
@{this. Jquery (). Validations (). Element ("User. Email "). Required ("Mailbox is required"). Email ("Please fill in the correct mailbox format");}
<input type= "Submit" value= "submitted"/>
</form>
</div>
<script type= "Text/javascript" >
@Html. Raw (this. Jquery (). Validations (). Toscripts ("#form"))
</script>
</body>
for a way to implement validation on a page, let me introduce what we should pay attention to.
1. Is that we must introduce the corresponding JS file, if we do not introduce Jquery.validation.js file, then the verification is not successful
2. The elements to be validated must be placed inside the form label
3. We should pay attention to the order when we validate elements through chained method, although it is possible to say any order, but we also need to adjust the order of verification according to business logic.
4. Finally, we submitted the submission through a submit button, someone may have to use Ajax and other ways to submit the page, I can tell you, I tried, so will not trigger the front-end JS verification
5. Finally we have to use the Toscript method to splice the validated JS, in MVC, the framework will automatically encode, so we ask the framework not to code. If the framework is not required
Do not encode, then the final JS result is encoded JS, this is not the result we want. You can look at the source code to see the results of the execution
Finally, there's a picture of the truth .
1. Initial interface Display
2. If some conditions are not met, then the error message will be displayed on the interface, which is customizable, of course. In my
When I debug the code, I found that under the IE9, sometimes the error message is not very real-time, the display in Firefox is normal, there may be some problems to solve. But does not affect the use.
To sum up, chained methods we actually often see that when we use LINQ, there are sometimes many ways to use links to improve the readability of the program. But when designing a chain-like approach, it's important to note that all chained methods return value types as much as possible, because it makes it easier for us not to grasp the order. Some friends will put forward different opinions, LINQ syntax is not all return value types are the same, but we need to know that when we use LINQ, the invocation order of the method is very important, right.
emphasize, the extension method does not actually add a method to the original class, but rather the equivalent of the static method in the calling static class.
It was dark and we were still trying. Strong we, will certainly have a better tomorrow.