MVC Validation Jquery.unobtrusive-ajax

Source: Internet
Author: User
Tags button type jquery library actionlink

Unobtrusive Ajax

Ajax (asynchronous JavaScript and XML abbreviations), as we can see, the focus of this concept is no longer the XML part, but the asynchronous part, which is a model for requesting data from the server in the background. The MVC framework has built-in support for unobtrusive Ajax, which allows us to define AJAX features with the help Mothod of MVC without having to use a large piece of JavaScript code in View.

This article directory:

How to use normal Ajax

Before we talk about unobtrusive Ajax in MVC, let's take a look at the common use of Ajax in MVC, where readers can compare and learn when reading the text.
Create a new MVC application (basic template), add a controller named Home, add a view for the auto-generated Index action, and edit the index.cshtml code as follows:

@{    viewbag.title = "Index";} <script type= "Text/javascript" >    function Test () {        $.ajax ({            URL: ' @Url. Action ("Gettestdata") ',            "POST ",success:function (Result) {$ ("#lblMsg"). Text (result.msg);}}         );    } </SCRIPT><H2 id= "lblmsg" >

Add an action named Test in HomeController, as follows:

Public Jsonresult Gettestdata () {    return Json (        new {msg = "Datetime from server:" + DateTime.Now.ToString ("hh:m M:ss ")}    );

Run the program, click the Test button, we can see the time from the background with Ajax:

Each time you click the Test button, it will refresh. This place needs to be reminded that the $.ajax () method In this example uses a POST request, and if a GET request is to be used, the Json method called in Test action needs to set the value of Jsonrequestbehavior to Allowget (the default is Denyget), as follows:

Public Jsonresult Gettestdata () {    return Json (        new {msg = "Datetime from server:" + DateTime.Now.ToString ("hh:mm: SS ")},        jsonrequestbehavior.allowget    );}

In addition, after changing to GET request, click the Test button multiple times, the time will not be refreshed. This is because the GET request returns the data in the cache for the same URL request in ASP.

What is unobtrusive Ajax

Unobtrusive Ajax is a common way to use JavaScript on Web pages. The term is not clearly defined, but it has the following basic principles (from Wikipedia):

    • The behavior (JavaScript code) is separated from the structure (Html markup) and presentation (CSS style) of the Web page.
    • JavaScript best Practices address traditional problems with the JavaScript language itself (such as lack of extensibility and developer coding style inconsistencies).
    • Resolves browser compatibility issues.

To deepen your understanding, look at one of the following unobtrusive AJAX "structure" sections of code:

... <form action= "/people/getpeopledata" data-ajax= "true" data-ajax-mode= "Replace" data-ajax-update= "#tableBody" Id= "Form0" method= "POST";

This is the code that MVC generates by calling the Ajax.beginform method after unobtrusive JavaScript is turned on. This code is completely separate from JavaScript, and the HTML tag tells JavaScript what the behavior is with some markup. The code in the separated JavaScript file (the Jquery.unobtrusive-ajax.min.js file introduced in MVC) is not written specifically for an HTML element in a particular Web page, that is, all functions are generic. This is the core idea of unobtrusive Ajax.

Unobtrusive Ajax is easier to read than normal Ajax, enhancing scalability and consistency, and maintaining ease of use.

Using MVC unobtrusive Ajax

Using unobtrusive Ajax in MVC is the first thing to "turn on" and need to do two actions. One is to configure the Web. config file under the root directory, and the unobtrusivejavascriptenabled value under the Configuration/appsettings node is set to True, as follows:

... <configuration> <appSettings> ...                     

The value of unobtrusivejavascriptenabled is set to True when the program is created, and sometimes only needs to be checked when developing. The second action is to introduce jquery libraries and jquery.unobtrusive-ajax.min.js files in a View that needs to use MVC unobtrusive Ajax, which is generally more common in/views/shared/_ Introduced in layout.cshtml, as follows:

<! DOCTYPE html>    <script src=" ~/scripts/ Jquery-1.8.2.min.js "></script>    <script src=" ~/scripts/jquery.unobtrusive-ajax.min.js "></ script>

Now let's do an example of using unobtrusive Ajax to get a simple list of users from the server. For this we need to prepare a model, as follows:

namespace Mvcapplication1.models {public    class person {public        string ID {get; set;}        public string Name {get; set;}        Public role role {get; set;}    }    public enum Role {        Admin, User, Guest    }}

I generally used to write the background method first, and then write the UI. Create a controller named people, and write the action you want to use in the controller with the following code:

public class Peoplecontroller:controller {public class Peoplecontroller:controller {private person[] Perso Ndata = {New Person {id = ' Zhangsan ', Name = ' Zhang San ', Role = role.admin}, new person {id = ' LiSi ', N AME = "John Doe", role = Role.user}, new person {ID = "Wangwu", Name = "Harry", Role = Role.user}, new Pers        on {ID = "Maliu", Name = "Caifan", Role = Role.guest}};        Public ActionResult Index () {return View ();  Partialviewresult getpeopledata (String selectedrole = "All") {ienumerable<person> data =            Persondata;                if (selectedrole! = "All") {Role selected = (role) Enum.parse (typeof (role), selectedrole);            data = Persondata.where (p = = P.role = = selected);        } return Partialview (data);        } public ActionResult GetPeople (String selectedrole = "All") {return View ((object) selectedrole);   } }} 

The Getpeopledata action method is added here, and the user data is obtained and passed to the Partialview method according to Selectedrole.

Next, create a partial view:/views/people/getpeopledata.cshtml for the Getpeopledata action, with the following code:

@using Mvcapplication1.models@model ienumerable<person> @foreach (person p in model) {    <tr>        <td >@p.ID</td>        <td>@p.Name</td>        <td>@p.Role</td>    </tr>}

Then create our main view/views/people/getpeople.cshtml with the following code:

 @using mvcapplication1.models@model string@{viewbag.title = "GetPeople";  Ajaxoptions ajaxopts = new Ajaxoptions {Updatetargetid = "tablebody"}; }  @using (Ajax.beginform (" Getpeopledata ", ajaxopts ) {<div> @Html. DropDownList ("Selectedrole", New SelectList (new[] {"All"}. Concat (Enum.getnames (typeof (Role)))) <button type= "Submit" >Submit</button> </div>}  pre>

First a Ajaxoptions object is created, and some of its properties (such as Updatetargetid, URL, HttpMethod, and so on) can be used to set how Ajax is requested. These properties are visible, such as Updatetargetid, which represents the element to be refreshed after an AJAX request is invoked (specified by element ID). The form that needs to be submitted to the server is then included in the Ajax.beginform () method, which submits the form data to the server via the submit element.

To make the operation look good, we add some styles to the table element in the _layout.cshtml file, as follows:

... table, TD, TH {     border:thin solid black; border-collapse:collapse; padding:5px     ; Background-color:lemonchiffon; Text-align:left; margin:10px 0; }...

Run the program, URL to/people/getpeople, click the Submit button in the page, the effect is as follows:

Ajax.beginform sends AJAX requests to the server by submitting a form, and MVC can also use the Ajax.actionlink () method to generate links to send Ajax requests to the server. Here we add this request in the getpeople.cshtml view:

<div>             @Ajax. ActionLink (role, "Getpeopledata",  new {selectedrole = role},             new ajaxoptions {Updatetargetid = "tablebody"}) @:&nbsp;    } </div>

The effect is the same as before:

Unlike Ajax.actionlink () and Ajax.beginform (), the former can only pass data to the server via URL parameters.

Unobtrusive how Ajax works

How does unobtrusive Ajax work?

When the Ajax.beginform method is called, the properties set by the Ajaxoptions object are converted to the attributes (tags) of the form element, which begins with Data-ajax, such as the form element generated by this example:

<form action= "/people/getpeopledata" data-ajax= "true" data-ajax-mode= "Replace" data-ajax-update= "#tableBody "id=" Form0 "method=" POST "...

When the getpeople.cshtml view loads and renders the Html page, the Jquery.unobtrusive-ajax.js library looks for all elements that have a value of true Data-ajax property, and then, based on other attribute values that begin with Data-ajax, The functions in the JQuery Library will know how to execute an AJAX request.

Configure Ajaxoptions

The properties in the Ajaxoptions class tell the MVC framework how to generate Ajax request-related JavaScript and Html code. It contains the following properties:

These properties VS Smart hints are well explained, not one of them, just choose a few representative speakers.

Ajaxoptions.url Property

In the example above, we specified the action name parameter in the Ajax.beginform () side, and MVC helped us generate the URL for the Ajax request (action= "/people/getpeopledata"). This is a problem, when the browser disables JavaScript, click the Submit button page will be a new request (non-AJAX request/people/getpeopledata), so the data returned by the server will directly replace the original page. To solve this problem, you can use the Ajaxoptions.url property because the Ajaxoptions.url property generates another URL specifically for the AJAX request. Here we make simple changes to the/views/people/getpeople.cshtml:

... @{    viewbag.title = "GetPeople";    Ajaxoptions ajaxopts = new Ajaxoptions {        Updatetargetid = "Tablebody",        = Url.action (" Getpeopledata ")    };} ... @using (Ajax.beginform (ajaxopts)) {    ...}

After the run we see the same results as before, stating that there is no difference in effect. But it produces a different form property:

<form id= "form0" action= "/people/getpeople " method= "POST" data-ajax-url= "/people/getpeopledata" data-ajax-update= "#tableBody" data-ajax-mode= "Replace" data-ajax= "true" > ...

It generates two URLs, respectively, for the Action property and the value of the Data-ajax-url property, which is generated by the Ajax.beginform () method based on the current controller and action name, which is the Url of the Ajaxoptions Property generated by the. When the browser does not disable JavaScript, the unobtrusive Ajax JS Library Gets the value of the Data-ajax-url property as a URL to the AJAX request. When JavaScript is disabled by the browser, the value of the natural Action property determines the URL that represents the submission, and the server returns to the original entire page. Although the local failed to refresh, but will not let the user feel that the site is doing badly.

Ajax loads data while giving feedback to the user

When loading the data takes a long time, in order to avoid the suspended animation status, should give the user a feedback message, such as "Loading ..." word. This can be done easily in MVC's unobtrusive Ajax through the Loadingelementid and loadingelementduration two properties of Ajaxoptions. Modify the getpeople.cshtml as follows:

@using Mvcapplication1.models@model string@{    viewbag.title = "GetPeople";    Ajaxoptions ajaxopts = new Ajaxoptions {        Updatetargetid = "Tablebody",        Url = url.action ("Getpeopledata"), C5/>loadingelementid = "Loading",        loadingelementduration = N,    };} 

Do not explain, run the program to see the effect:

Popup confirmation dialog box

It is also convenient to use the unobtrusive Ajax Pop-up confirmation dialog in MVC, setting the value of the Ajaxoptions.confirm property to be as follows:

... @{    viewbag.title = "GetPeople";    Ajaxoptions ajaxopts = new Ajaxoptions {        Updatetargetid = "Tablebody",        Url = url.action ("Getpeopledata"),        Loadingelementid = "Loading",        Loadingelementduration = +,        = "Do you wish to request new data?"     }; ...

The dialog box that pops up is as follows:

Ajax callback function

The Onbegin, OnComplete, OnFailure, and Onsuccess properties in the Ajaxoptions class allow us to define a callback function at a state point in the AJAX request cycle. Look at the specific usage.

Add the following 4 callback functions to the getpeople.cshtml file:

<script type= "Text/javascript" >     function Onbegin () {         alert ("This is the Onbegin Callback");     }    function onsuccess (data) {         alert ("This is the Onsuccesscallback:" + data);     }     function onfailure (request, error) {         alert ("This is the OnFailure Callback:" + error);     }     function OnComplete (request, status) {         alert ("This is the OnComplete Callback:" + status);     } </script>

Then set the 4 event properties of the Ajaxoptions object:

@{ viewbag.title = "GetPeople"; Ajaxoptions ajaxopts = new Ajaxoptions { Updatetargetid = "Tablebody", Url = url.action ("Getpeopledata"), C5/>onbegin = "Onbegin", onfailure = "OnFailure", onsuccess = "onsuccess", oncomplete = "OnComplete" c9/>};}

To run the program, pop up three message boxes as follows:

The most common of these four event attributes is the onsuccess and onfailure two properties, as we often do with the returned Json data in the onsuccess callback function.

In fact, I personally prefer the normal way of using Ajax. Ajax.beginform () and Ajax.actionlink () use less, accustomed to using html.beginform () or Html.ActionLink () and handwritten jQuery Ajax code instead.

Reference: "Pro asp 4 4th Edition"

MVC Validation Jquery.unobtrusive-ajax

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: 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.