ASP. NET MVC Development Basics Learning notes: Four, checksum, Ajax and filters

Source: Internet
Author: User
Tags httpcontext types of filters jquery library

One, check-form not that you want to mention, you can mention 1.1 dataannotations (data annotations)

Attributes that are located in the System.ComponentModel.DataAnnotations namespace specify validation for each field in the data model. These attributes are used to define common validation patterns, such as scope checks and required fields. The dataannotations feature enables MVC to provide client and server validation checks so that you don't have to do extra coding to control the effectiveness of your data .

By adding the dataannotations of data descriptions to the model classes, we can easily add validation capabilities to the application. DataAnnotations allows us to describe the validation rules that you want to apply on model properties, and ASP. NET MVC will use these dataannotations and then return the appropriate validation information to the user.

Among the many built-in verification features that DataAnnotations provides for us, four of them are:

(0) [DisplayName]: Display Name – Defines the prompt name for form fields

(1) [Required]: Must – Indicates that the property is a field that must provide content

(2) [stringlength]: String length – Defines the maximum length of a property of a string type

(3) [Range]: Range – provides the maximum and minimum values for a property of a numeric type

(4) [regularexpression]: Regular expression – Specifies that data field values in Dynamic Data must match the specified regular expression

1.2 Verifying the model with the DataAnnotations

Suppose we have a userinfo entity in our model, which is defined as follows:

    public class UserInfo    {public        int Id {get; set;}        public string UserName {get; set;}        public int Age {get; set;}    }

The properties of userinfo are simple, only three: Id,username and age three fields; now we can add validation features to it to see the powerful checksum that we have provided.

(1) Non-null verification

To add an attribute:

[Display (name= "username")]    [Required (errormessage = "* Name required")]public string UserName {get; set;} [Display (Name = "age")] [Required (errormessage = "* Ages required")]public int age {get; set;}

Verify the effect:

(2) String length verification

To add an attribute:

[Display (name= "username")] [Required (errormessage = "* Name required")] [Stringlength (5, errormessage = "* length must be less than 5")]public string UserName {get; set;}

Verify the effect:

(3) Scope verification

To add an attribute:

[Display (Name = "age")] [Required (errormessage = "* Age required")] [Range]]public int Age {get; set;}

Verify the effect:

(4) Regular expression validation

Add attribute: Verify that user input is numeric, regular expression matches

[Display (Name = "age")] [Required (errormessage = "* Age required")] [Range (18, 120)] [RegularExpression (@ "^\d+$", errormessage = "* Please enter a valid number")]public int age {get; set;}

Verify the effect:

(5) to browse the generated HTML code

As can be seen, our browser-side checksums are implemented by setting custom properties for HTML tags, and the various check attributes that we add to the model will generate a specific property on the client, for example: data-val-length-max= "5" With data-val-length= "* length must be less than 5" corresponds to [Stringlength (5, errormessage = "* length must be less than 5")]. Then, with jquery validate, the client checks before each commit, and if there are non-conforming rules in the checksum match, the message is displayed in a specific span label (class= "Field-validation-valid"). and prevent this form from submitting operations.

1.3 Precautions for using dataannotations

(1) First of all, to ensure that the page that needs to be verified introduces the specified number of JS files:

<script src= "@Url. Content (" ~/scripts/jquery.validate.min.js ")" Type= "Text/javascript" ></script>
<script src= "@Url. Content (" ~/scripts/jquery.validate.unobtrusive.min.js ")" Type= "Text/javascript" ></ Script>

Of course, the jquery library JS file is also necessary, and in the above two JS introduced before;

(2) in the appsettings of Web. config, client authentication is supported by default (default support in MVC3.0 and later versions, MVC2.0 needs to be modified):

<!--whether to enable global client-side checksum--><add key= "clientvalidationenabled" value= "true"/><add key= " Unobtrusivejavascriptenabled "value=" true "/>

PS: Unobtrusive JavaScript has three layers of meaning:

First, in the HTML code will not arbitrarily insert the Javsscript code, only add some additional property values in the tag, and then the referenced script file recognition and processing;

Second, the added functionality through the script file is a progressive enhancement, when the client does not support or disable the javsscript when the Web page provides functionality can still be achieved, but the user experience will be reduced;

Third, can be compatible with different browsers.

(3) In action if you want to verify that the client has passed a checksum, you can do so by using the following code:

        [HttpPost]        Public ActionResult Add (UserInfo UserInfo)        {            if (modelstate.isvalid)            {                 //to Does fun            }            return Redirecttoaction ("Index");        }

If verified, the IsValid property (bool type) of Modelstate becomes true, and vice versa is false.

Two Ajax approaches under ASP. 2.1 Using jquery Ajax

First, the use of this approach in ASP. NET MVC is consistent with the way common WebForm is developed, and it is important to note that the request is a controller action under different URL addresses, for example, the URL requested in WebForm is usually/ajax/ Userhandler.ashx, and the URL requested in MVC is typically:/user/getall.

For example, we add a button to a view that uses Ajax to get a server-side time:

Add an action to return time to the home controller:

Public ActionResult Getserverdate () {return Content (DateTime.Now.ToString ());}

Add a section of jquery code to the view and bind a click event to the Btnjquery button:

    $ (function () {            $ ("#btnJQuery"). Click (function () {                $.post ("/home/getserverdate", {}, function (data) {                    if (data! = NULL) {                        $ ("#spTime"). HTML (data);});});    

Here, we send an asynchronous POST request via jquery Ajax, get the server time result, and display it in the span tag:

At this point, an MVC page with jquery Ajax is done. However, this is only one of the simplest examples of Ajax, which is often more complex in real-world development.

It is important to note that:

(1) If you are using a Get-mode commit in jquery Ajax, note that when using JSON to return Jsonresult, be careful to set the second parameter to allow the Get-commit method: Return Json ("", Jsonrequestbehavior.allowget), otherwise you do not have permission to execute the action method you want to request by using the Get method.

(2) In AJAX development, it is important to note that the parameters of the Ajax method are set correctly, especially the parameter names are consistent with the parameter names in the action;

(3) If [HttpPost] or [HttpGet] is set for it in action, the submission is consistent with the tag of the action;

2.2 Using Microsoft Ajax methods

In addition to the use of jquery ajax in ASP., Microsoft provides us with another set of practical and simpler Ajax scenarios, which we would call Microsoft Ajax.

(1) First:

A Microsoft-provided JS script needs to be introduced into the page: Actually, it's jquery.unobtrusive-ajax.js.

<script src= "~/scripts/jquery-1.7.1.min.js" ></script><script src= "~/Scripts/ Jquery.unobtrusive-ajax.min.js "></script>

Ensure that unobtrusive JavaScript is enabled in Web. config

<add key= "unobtrusivejavascriptenabled" value= "true"/>

(2) Second, use the Ajax.beginform method to construct a form form:

       

It is important to note that:

The ①ajax.beginform does not provide a closed method and needs to be closed with using mates;

Settings for the ②ajaxoptions parameter:

Does the httpmethod represent the post or get mode for this AJAX request? Here is the post mode;

Confirm represents the confirmation dialog that is presented after clicking the Submit button and gives the user a given prompt, here is: Are you sure you want to submit?

Insertionmode whether the data after the request is to be replaced or appended, the general choice to replace, that is, replace;

Updatetargetid represents the ID of the DIV tag that needs to be replaced, and here is a span tag that represents the information that needs to be displayed in this span;

Onsuccess represents the request after the successful implementation of the callback method, is a JS method, can be customized, here is a function aftersuccess () method;

        function aftersuccess (data) {            //alert ("You have successfully obtained the information:" + data);        }

Loadingelementid= "Loading" is an interesting attribute that represents a prompt to be loaded in order to provide a good user experience during an AJAX request, and this loadingelementid represents the ID of a hint's div area. Here mainly refers to the ID loading of this div, which has a GIF picture and a word: is getting, please wait ... The prompt.

<div id= "Loading" style= "Display:none" >       is getting in, please wait ...</div>

To show the effect of loading hints, we artificially modify the action method, using Thread.Sleep (3000) to delay the request return time

        Public ActionResult getserverdate ()        {            System.Threading.Thread.Sleep (+);            Return Content (DateTime.Now.ToString ());        }

OK, now we can look at how it works:

This is where our Microsoft Ajax completes the simplest demo. So, we can't help but wonder how Microsoft Ajax did it? As with the calibration, let's look at the resulting form form to find out:

It turns out that the parameters we set in Ajaxoptions are also parsed into the custom properties of the form, and their corresponding relationships are as follows:

Third, for AOP-asp.net MVC default Filter 3.1 filter initially a larger project will always have related AOP-oriented components, and MVC (specifically: ASP. NET MVC, All of the following) in the project, we want to do some special things (such as authentication, logs, exceptions, behavior interception, etc.) before or after the execution of the action, rather than let the MVC developer care about and write this part of the duplicated code. Then, we can intercept the implementation through AOP, and in the MVC project we can directly use the filter features provided by it to help us solve the complex AOP without our own implementation.
AOP:Aspect Oriented Programming (AOP) is a hot topic. AOP, the domestic roughly translated "plane-oriented programming."  In order to extract the facets in the process of business processing, it is confronted with a step or stage in the process to obtain the isolation effect of the low coupling between the parts of the logic process. AOP enables the isolation of parts of the business logic, which reduces the coupling between parts of the business logic, improves the reusability of the program, and improves the efficiency of development. The main functions are: Logging, performance statistics, security control, transaction processing, exception handling and so on.
3.2 Several default filters provided by Microsoft

Microsoft has provided us with four types of filters (filter) By default, as shown in:

Here, we mainly look at the use of Actionfilter (action filter) and Exceptionfilter (Exception filter):

(1) Action Filter

ActionFilterAttribute Iactionfilter and Iresultfilter are implemented by default. While ActionFilterAttribute is an abstract type, it cannot be used directly because it cannot be instantiated, so we want to use it to inherit it before it can be used.

① Therefore, we first create a new class in the models, named: Myactionfilterattribute (at the end of the attribute compared to the code specification), and make it inherit from ActionFilterAttribute, Then override the virtual method provided by the base class:

    public class Myactionfilterattribute:actionfilterattribute {public string Name {get; set;} <summary>////action execute this method before///</summary>//<param name= "Filtercontext" >            Filter context </param> public override void OnActionExecuting (ActionExecutingContext filtercontext) { Base.            OnActionExecuting (Filtercontext);        HttpContext.Current.Response.Write ("<br/>onactionexecuting:" + Name); }///<summary>///action after///</summary>//<param name= "Filtercontext" &G            t; filter context </param> public override void OnActionExecuted (ActionExecutedContext filtercontext) { Base.            OnActionExecuted (Filtercontext);        HttpContext.Current.Response.Write ("<br/>onactionexecuted:" + Name); }///<summary>//ActionResult Execute this method before///</summary>//<param name= "filTercontext "> Filter context </param> public override void Onresultexecuting (ResultExecutingContext filtercontext) {base.            Onresultexecuting (Filtercontext);        HttpContext.Current.Response.Write ("<br/>onresultexecuting:" + Name); }///<summary>//ActionResult Execute this method first///</summary>//<param name= "filt        Ercontext "> Filter context </param> public override void Onresultexecuted (ResultExecutedContext filtercontext) {base.            Onresultexecuted (Filtercontext);        HttpContext.Current.Response.Write ("<br/>onresultexecuted:" + Name); }    }

Here we rewrite four virtual methods, each representing the business logic that needs to be executed before and after the action executes, as well as the business logic that needs to be executed before and after the result is executed. The result here mainly refers to when we return the results in action (for example: Return Content ("Hello filter!"); ), before and after the logical processing to be performed.

For example: We want to check whether the user is logged in before each action executes, can determine whether the user session exists in onactionexecuting, if there is a specific business code to continue to execute the action, if it does not exist, redirect the page to the landing page, The action business code behind is no longer executed.

② now has a custom filter, how do we apply it to the action? There are three ways of doing this:

One is to specify this filter for an action on a controller:

        [Myactionfilter (Name = "Filter Action")]        Public ActionResult Filter ()        {            Response.Write ("<p>action is trying to implement in ...</p>");            Return Content ("<p>ok: View successfully rendered </p>");        }

The second is to specify this filter for all actions of a controller:

    [Myactionfilter (name= "Home Filter")]    public class Homecontroller:controller    {    }

However, it is important to note that if you assign a filter to a controller and a filter to an action in that controller, the specific action will be the closest filter to its definition, which is a Priority order problem: The action's filter priority is higher than the controller's filter.

The third is to assign this filter globally to all controllers in this project: Change the Filterconfig class in App_start, which has the lowest priority .

        public static void Registerglobalfilters (Globalfiltercollection filters)        {            filters. ADD (New Handleerrorattribute ());            Register a Custom action filter: the lowest priority, but it can affect all controllers and action            filters. ADD (New Myactionfilterattribute () {Name = "Global Controller"});        

③ Now let's look at the specific effect:

Can see, our/home/filter This action only two lines of code, one sentence Response.Write, the other is Return Content (); The OnActionExecuting filter method was executed prior to Response.Write, and then the onactionexecuted filter method was executed; we just said that the return statement in action represents result, then it was executed before result. The Onresultexecuting filter method is followed by the onresultexecuted filter method. Here is only to show that in the actual development of the need to write some specific business logic processing, such as: To determine the user's login status, record the user's operation log and so on.

(2) Exception Filter

① Similarly, create a new class in models named: Myexceptionfilterattribute, and inherit it from Handleerrorattribute.

    public class Myexceptionfilterattribute:handleerrorattribute    {public        override void Onexception ( Exceptioncontext filtercontext)        {            base. Onexception (filtercontext);            HttpContext.Current.Response.Redirect ("/home/index");        }    }

Here, overriding the Onexception method of the base class, here just to demonstrate the effect, no exception is handled. In real-world development, you need to get the exception object and log it into the journal. For example, the following section of code:

     public override void Onexception (Exceptioncontext filtercontext)        {            base. Onexception (filtercontext);            Gets the system exception message record            string strexception = FilterContext.Exception.Message;            if (!string. IsNullOrEmpty (strexception))            {                //Use Log4net to record exception information                Exception Exception = filtercontext.exception;                if (Exception! = null)                {                    Loghelper.writeerrorlog (strexception, exception);                }                else                {                    loghelper.writeerrorlog (strexception);                }            }            FilterContext.HttpContext.Response.Redirect ("~/globalerrorpage.html");        }

② has an exception filter, how do we apply it to the project? The answer is also in App_start, or in the Filterconfig class, add a new code to register:

    public class Filterconfig    {public        static void Registerglobalfilters (Globalfiltercollection filters)        {            filters. ADD (New Handleerrorattribute ());            Register a Custom action filter: the lowest priority, but it can affect all controllers and action            filters. ADD (New Myactionfilterattribute () {Name = "Global Controller"});            Register the custom exception filter            filters. ADD (New Myexceptionfilterattribute ());        }    }

③ to test, we add an action that allows an exception to occur: Dividedbyzero

        Public ActionResult Exception ()        {            int a = ten;            int b = 0;            int c = A/b;            Return Content ("Exception is happened.");        }

④ When we test this action, we find that the system executes a custom exception filter, changing our request to redirect to the action of index.

Resources

(1) Jing Jinnan, four types of authentication programming under ASP. http://www.cnblogs.com/artech/p/asp-net-mvc-validation-programming.html

(2) Jing Jinnan, four ways to verify programming under ASP. [Sequel], http://www.cnblogs.com/artech/p/asp-net-mvc-4-validation.html

(3) Mullen, "ASP 2014 Special Tutorial", http://bbs.itcast.cn/thread-26722-1-1.html

(4) w809026418, "model validation using DataAnnotations in MVC", http://www.cnblogs.com/haogj/archive/2011/11/16/2251920.html

(5) Liu Junfeng, "unobtrusive Ajax in ASP.", http://www.cnblogs.com/rufi/archive/2012/03/31/unobtrusive-ajax.html

ASP. NET MVC Development Basics Learning notes: Four, checksum, Ajax and filters

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.