Create a link using the Help function
MVC provides some help functions to create links that automatically adjust the generated URLs based on the Path mapping table:
Description |
Example |
Output results |
Application-Relative URLs |
Url.content ("~/content/site.css") |
/content/site.css |
Link to the Controller action |
Html.ActionLink ("My Link", "Index", "Home") |
<a href= "/" >my link</a> |
The URL of the action |
Url.action ("GetPeople", "people") |
/people/getpeople |
URL to use path mapping |
Url.routeurl (New {controller = "people", action= "GetPeople"}) |
/people/getpeople |
Links Using path mappings |
Html.routelink ("My Link", new {controller = "people", action= "GetPeople"}) |
<a href= "/people/getpeople" >my link</a> |
Links to named path mappings |
Html.routelink ("My Link", "Formroute", new {controller = "people", action= "GetPeople"}) |
<a href= "/app/forms/people/getpeople" >my link</a> |
Using MVC unobtrusive Ajax
MVC built on the support of jquery-based unobtrusive Ajax, which is called unobtrusive Ajax because it does not use XML as much as regular Ajax. To use unobtrusive Ajax, you first need to turn on unobtrusivejavascriptenabled support in the Configuration/appsettings section of Web. config:
At the same time we need to refer to the relevant JavaScript files, you can put references to these script files in the layout file _layout.cshtml:
<! DOCTYPE html>
Jquery-1.7.1.min.js is the core repository of jquery, Jquery.unobtrusive-ajax.min.js provides AJAX functionality (based on the jquery Library), and the. min in the file name represents a reduced version that is almost impossible to debug, and can be used at development time with a non-. Min version , and then use the. Min version when publishing.
Use unobtrusive Ajax formsThe following example shows how to use an AJAX form, starting with the controller:
Using system;using system.collections.generic;using system.linq;using system.web;using System.Web.Mvc;using Helpermethods.models;namespace helpermethods.controllers{public class Peoplecontroller:controller {privat E person[] Persondata = {New Person {FirstName = ' Adam ', LastName = ' Freeman ', Role = role.admin}, new person {FirstName = "Steven", LastName = "Sanderson", role = role.admin}, new person {FirstName = "Jacqui", LastName = "Griffyth", role = Ro Le. User}, new person {FirstName = "John", LastName = "Smith", Role = Role.user}, new person {FirstName = "Anne", LastName = " Jones ", 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 () method filters the person list according to the selected role, returning a partial view, corresponding to the getpeopledata.cshtml:
@using Helpermethods.models@model ienumerable<person> @foreach (person p in model) { <tr> <td >@p.FirstName</td> <td>@p.LastName</td> <td>@p.Role</td> </tr > }
In the Getpeople view we call Getpeopledata () to create an AJAX form at the same time:
@using Helpermethods.models@model string@{ viewbag.title = "GetPeople"; Ajaxoptions ajaxopts = new Ajaxoptions { Updatetargetid = "Tablebody" };}
Ajax.beginform () creates an Ajax form that uses the Ajaxoptions object as a parameter to generate the HTML result:
When the browser requests the Getpeople page jquery.unobtrusive-ajax.js scan the Data-ajax=true unit to confirm that this is an AJAX form, click Submit does not refresh the entire page, but with the/people/ Getpeopledata The returned result replaces the contents of the Tablebody.
Ajax OptionsAjaxoptions controls how asynchronous requests are made to the server, including these properties:
Property |
Description |
Confirm |
Displays a message to the user when an asynchronous request is started to confirm |
HttpMethod |
Set the HTTP method of the request, which must be a GET or post |
Insertionmode |
How to embed the HTML returned by the server results, which can be InsertAfter, InsertBefore, Replace (default) |
Loadingelementid |
Loading cell element ID to display when specifying AJAX requests |
Loadingelementduration |
Loading element Animation display duration |
Updatetargetid |
The element ID that the request returned the result to insert |
Url |
URLs for AJAX form submissions |
The Getpeople view above the Ajax form submission URL is/people/getpeopledata, if the user prohibits the Java script, the submission form returns the result is only getpeopledata partial view, We can specify the URL of the AJAX request directly in Ajaxoptions to resolve:
@using helpermethods.models@model string@{viewbag.title = "GetPeople"; Ajaxoptions ajaxopts = new Ajaxoptions {Updatetargetid = "tablebody", Url = Url.action ("Getpeopledata"), Loadingelementid = "Loading", Loadingelementduration = $, Confirm = "Do you wish to request new D Ata? "};}
Generated form HTML:
The URL of the form submission is still/people/getpeople, even if the Java script is forbidden to return the GetPeople page, the URL of the AJAX request is specified as/people/getpeopledata by Data-ajax-url. We also set Ajaxoptions.loadingelementid to loading, which is a diplay:none-style div element that displays only one second in Ajax asynchronous requests (Loadingelementduration = 1000). Ajaxoptions.confirm= "Do you wish to request new data?", the page Message dialog box asks when each AJAX request (the dialog box message sets the "Do you wish to request n EW data? " )。
Ajax LinksIn the above example, we use the form to submit data, if the use of links to do Ajax asynchronous request can do this:
...<div> @foreach (String role in Enum.getnames (typeof (role))) {<div class= "Ajaxlink" > @Ajax. ActionLink (r OLE, "Getpeopledata", new {selectedrole = role}, new Ajaxoptions {Updatetargetid = "tablebody"}) </div>} </div> ...
Here a link is generated for each element in the role enumeration, similar to the resulting LINK element:
When you click on a link, the HTML data returned by Ajax is used to replace the tablebody element with the same effect as submitting an AJAX request using a form. Similarly, if Java scripting is disabled, the returned results are just getpeopledata partial views, which we can improve:
The address of the link request is the URL of the Getpeople,ajax request and is only getpeopledata, and the requested HTML result is tablebody.
Ajax callbacksThe Ajaxoptions class exposes a set of properties that allow us to specify a Java script function that calls these script functions during the AJAX request cycle:
Property |
jquery Events |
Description |
Onbegin |
Beforesend |
Called before the AJAX request is sent |
OnComplete |
Complete |
Called when the request succeeds |
OnFailure |
Error |
Called when a request fails |
Onsuccess |
Success |
Whether the request succeeds or not is called when the request is complete |
In conjunction with the callback function, we can further modify the above example by first modifying the controller's Getpeopledata method:
public ActionResult 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); } if (Request. Isajaxrequest ()) {var formatteddata = data. Select (p = = new {FirstName = P.firstname, LastName = P.lastname, role = Enum.getname (typeof (Role), P.role)}); Return Json (Formatteddata, jsonrequestbehavior.allowget); } else {return Partialview (data); } }
We use Request.isajaxrequest to determine whether the request is from Ajax, which is based on the browser's inclusion of X-requested-with=xmlhttprequest in the header in the AJAX request. If the request comes from Ajax, the Controller method returns the Jsonresult object created by JSON (data, Jsonrequestbehavior.allowget), and the default JSON data is sent only in the POST request. The second parameter specifies that Jsonrequestbehavior.allowget allows JSON data to be used in a GET request. The MVC framework is responsible for JSON encapsulation of Formatteddata, and the encapsulated format is determined by MVC's attempt to use the most appropriate method, where the JSON data returned is similar:
In the view we process the returned JSON data in the Ajaxoptions onsucess callback function:
@using Helpermethods.models@model string@{viewbag.title = "GetPeople"; Ajaxoptions ajaxopts = new Ajaxoptions {//updatetargetid = "tablebody", Url = Url.action ("Getpeopledata" ), Loadingelementid = "Loading", Loadingelementduration = +, onsuccess = "ProcessData"};} <script type= "Text/javascript" > Function processdata (data) {var target = $ ("#tableBody"); Target.empty (); for (var i = 0; i < data.length; i++) {var person = data[i]; Target.append ("<tr><td>" + person.) FirstName + "</td><td>" + person. LastName + "</td><td>" + person. Role + "</td></tr>"); }}</script>The script function processdata is called at Ajaxoptions's onsuccess callback, which processes the JSON data returned by the request and splits out the individual person objects, overwriting the contents of the Tablebody tag directly based on that data. So we no longer need to specify the element to replace the content with Ajaxoptions through Updatetargetid.
The above is a summary of the contents of the fourth edition of the Apress Pro ASP. NET MVC 4, as described in the original http://www.apress.com/9781430242369.
ASP. NET MVC 4 (eight) URL links and Ajax helper functions