. Net 3.0 adds a syntax sugar to the extension method. In fact, the essence of the extension method is to call the static method of the class. Although the extension method only changes the way we write code, however, if we use it properly, it will bring us a huge improvement in coding efficiency. I will not elaborate on the use of the C # extension method. The use of the extension method will be described by posting code segments.
Copy codeThe Code is as follows: public static class Extensions
{
Public static string EndWith (this string str)
{
Return str + "@";
}
}
For this very simple code, I believe everyone should understand that we can see that the use of the extension method is to define a static method in a static class and add this to the method parameters.
The extension method is simpler. The following code snippet is the string extension of the extension method. @Copy codeThe Code is as follows: string str = "";
Response. Write (str. EndWith ());
The extension method is not the focus of this project. The focus of this project is to describe how to use the extension method to chained verification of pages in MVC 3. There are many ways to verify Mvc. Among them, we often use Model verification, which is the most direct and most effective method for our operations, multiple conditions can be verified for a field. However, this verification method has one drawback: we cannot directly view the verification of this field on the page, unless we view it at the Model layer, but a project is usually divided into project groups, we are not necessarily responsible for developing the Model layer, so we will encounter a communication problem. We all know that the communication cost for programmers is very high.
Now we provide another method for page verification. This method can also verify multiple conditions for a page element, which is performed on the client. To use this verification, we must understand a jquery plug-in, that is, the jquery. validation. js file, which is a js file for element verification.
What else do we need to know? Which class does the Razor view of Mvc 3 directly inherit from? I believe many of my friends will not hesitate to say "ViewPage". Of course, this cannot be said to be wrong, because Mvc 2 does inherit from the ViewPage base class, but in the Razor view, it is inherited from the WebViewPage class. If your extension method is extended to the ViewPage, sorry, you cannot see this extension method on the page unless it inherits from the WebViewPage class. I hope you will pay attention to class inheritance when extending the PAGE method.
After talking about the preparations, let's start with the subject, paste the code first, and then analyze it gradually.Copy codeThe Code is as follows: namespace MvcWeb. Extensions
{
Public class JqueryHelper
{
Public ViewContext {get; private set ;}
Public WebViewPage ViewPage {get; private set ;}
Public 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)
{
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 {get; private set ;}
Public JqueryValidations (WebViewPage)
{
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 Email (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 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 Email (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;
}
}
}
The JqueryHelper class is defined in this Code, which is an extension of WebViewPage. There is a ToScript method. We should note that this method displays a piece of spliced js on the page, that is, jquery. validation. js will use to verify the js of the page element.
I will not elaborate on the specific code. Let me introduce the basic idea. First, we define a JqueryHelper class, and then define a JqueryValidation class to verify the page elements. The result returned by each verification method is an object of the JqueryValidation class, so that we can perform the chained operation.
You can use Dictionary to store the value of the verified Tag Name, error information, and verification rules. Then, based on these values, splice the JavaScript code that can be submitted in ToScript.
Now, let's look at the result and you will be more aware of the purpose of this chained method.Copy codeThe Code is as follows :@{
Layout = null;
}
@ Using MvcWeb. Extensions
<! DOCTYPE html>
<Html>
<Head>
<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>
</Head>
<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 ");}
<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 ("email is Required "). email ("enter the correct Email format ");}
<Input type = "submit" value = "submit"/>
</Form>
</Div>
<Script type = "text/javascript">
@ Html. Raw (this. Jquery (). Validations (). ToScripts ("# form "))
</Script>
</Body>
</Html>
For how to implement verification on the page, I will introduce what we should pay attention
1. We must introduce the corresponding js file. If we do not introduce the jquery. validation. js file, the verification will fail.
2. The elements to be verified must be placed in the form tag.
3. We should pay attention to the order when verifying elements through the chained method. Although any order is acceptable, we also need to adjust the verification order according to the business logic.
4. Finally, we use a submit button to submit the page. Someone may use ajax or other methods to submit the page. I can tell you that I tried it, so that the front-end js verification will not be triggered.
5. Finally, we must use the ToScript method to splice the verification js Code. In Mvc, the framework will automatically encode the code, so we require that the framework not be encoded. If no framework is required
Do not encode. The final js result is the encoded js, which is not our result. You can view the source code to view the execution result.
Finally, there is a picture with truth.
1. Initial interface display
2. If some conditions are not met, the error message will be displayed on the interface. Of course, this can be customized. In my
When I debug the code, I found that in IE9, sometimes the error message is not displayed in real time, and the display under Firefox is normal, and some problems may need to be solved. But it does not affect usage.
To sum upIn fact, we often see the chained method. When using linq, there are sometimes many method links to improve the readability of the program. However, when designing a chained method operation, we must note that the return values of all chained methods are of the same type as possible, because this makes it easier for us to understand the sequence. Some Garden friends may come up with different opinions. Not all types of return values in the linq syntax are the same, but we need to know that when we use linq, the call sequence of methods is very important, right.
EmphasizeThe extension method does not actually add a method to the original class, but is equivalent to the static method implementation in the called static class.
The sky is dark, and we are still working hard. If we are strong, we will certainly have a bright future.