First, the Ajax of jquery:
1. Use jquery to form an AJAX request:
1) Create a new Ajaxexamples project and add the Customajax controller:
namespace ajaxexamples.controllers{ publicclass customajaxcontroller:controller { Public actionresult Index () { return View (); } Public ActionResult PrivacyPolicy () { return partialview (); }}}
2) Add a custom jquery code:
$ (document). Ready (function () { $ (' #privacyLink '). Click (function (event) { Event.preventdefault (); var url = $ (this). attr (' href '); $ (' #privacy '). Load (URL); } );
3) Add PrivacyPolicy partial view:
< H2 > Privacy Policy </h2> Keep it secret Oh ~ ~
4) Add the index view:
@Html. ActionLink ("Show Privacy Policy", "PrivacyPolicy", NULL, new {id= "Privacylink"})<DivID= "privacy"></Div><Scripttype= "Text/javascript"src= "@Url. Content ("~/scripts/jquery-1.10.2.min.js ")"></Script>@* The default layout view has been introduced jquery however, the operation error, so again introduced *@<Scripttype= "Text/javascript"src= "@Url. Content ("~/scripts/ajaxdemo.js ")"></Script>
If the user disables JavaScript, the above page will go to the PrivacyPolicy page, but because the PrivacyPolicy action returns a partial view, it is not beautiful to resolve this issue to modify the PrivacyPolicy action:
Public ActionResult PrivacyPolicy () { if (Request.isajaxrequest ())// Check if Ajax calls { return Partialview (); } return View (); }
2. Submit form data using Ajax:
1) Introduce AddComment action:
namespaceajaxexamples.controllers{ Public classCustomajaxcontroller:controller {Private Staticlist<string> _comments =Newlist<string> ();//Save a comment list PublicActionResult Index () {returnView (_comments); } PublicActionResult PrivacyPolicy () {if(Request.isajaxrequest ())//Check whether Ajax calls { returnPartialview (); } returnView (); } [HttpPost] PublicActionResultaddcomment(stringcomment) {_comments. ADD (comment);//Save new Comment if(Request.isajaxrequest ()) {viewbag.comment=comment; returnPartialview ();//send comments to a view } returnRedirecttoaction ("Index"); } }}
2) Add addcomment partial view:
<li> @ViewBag .comment</li>
3) Modify the index view:
@model IEnumerable<string><ulID= "Comments">@foreach (var comment in Model) {<Li>@comment</Li> }</ul>@using (Html.BeginForm ("AddComment", "Customajax", FormMethod.Post, new {id = "commentform"})) {@Html. TextArea ("C Omment ", new {rows = 5, cols =.)<BR/> <inputtype= "Submit"value= "Add Comment" />}<Scripttype= "Text/javascript"src= "@Url. Content ("~/scripts/jquery-1.10.2.min.js ")"></Script>@* The default layout view has been introduced jquery however, the operation error, so again introduced *@<Scripttype= "Text/javascript"src= "@Url. Content ("~/scripts/ajaxdemo.js ")"></Script>
4) Modify Ajaxdemo.js:
$ (document). Ready (function () {$ ( ' #commentForm '). Submit (function var data = $ (this ). Serialize (); Span style= "color: #008000;" >// serialize form to string var url = $ (this ). attr (' action ' ); $.post (URL, data, function (response) { $ ( ' #comments '). Append (response); // }); });});
Ajax Helper for asp:
1.ajax.actionlink:
1) Add Jquery.unobtrusive-ajax.js to the project: Enter Install-package microsoft.jquery.unobtrusive.ajax–version in the Program Management Pack Manager Console 3.0.0
2) Modify the index view:
@Ajax. ActionLink ("Show Privacy Policy", "PrivacyPolicy", new Ajaxoptions{insertionmode = Insertionmode.replace, Updatetargetid = "Privacy"})<DivID= "privacy"></Div><Scripttype= "Text/javascript"src= "@Url. Content ("~/scripts/jquery-1.10.2.min.js ")"></Script>@* The default layout view has been introduced jquery however, the operation error, so again introduced *@<Scripttype= "Text/javascript"src= "@Url. Content ("~/scripts/jquery.unobtrusive-ajax.min.js ")"></Script>
The HTML generated in the Start Debugging View page is as follows:
<data-ajax= "true" data-ajax-mode= "Replace" Data-ajax-update= "#privacy" href= "/customajax/privacypolicy"> Show Privacy Policy </a>
The Data-ajax Tag property is used to indicate that the hyperlink executes asynchronously, Data-ajax-mode and data-ajax-update correspond to ajaxoptions objects.
When the page loads, the script in Jquery.unobtrusive-ajax will find all the links with Data-ajax tag properties and attach a click event. Similarly, if the browser disables JavaScript, the link behaves as if it were a regular hyperlink.
2.ajax.beginform:
To modify the index view:
<ulID= "Comments"></ul>@using (Ajax.beginform ("AddComment", new ajaxoptions {Updatetargetid = "comments", Insertionmode = Insertionmode.insertafter}) {@Html. TextArea ("Comment", new {rows=5,cols=50})<BR/> <inputtype= "Submit"value= "Add Comment" />}<Scripttype= "Text/javascript"src= "@Url. Content ("~/scripts/jquery-1.10.2.min.js ")"></Script>@* The default layout view has been introduced jquery however, the operation error, so again introduced *@<Scripttype= "Text/javascript"src= "@Url. Content ("~/scripts/jquery.unobtrusive-ajax.min.js ")"></Script>
3.Ajax options:
4. Differences from previous versions of ASP. NET MVC:
Although Ajax helpers have been part of ASP. NET MVC since the first version, jquery is now the default. In previous versions of the framework, these helpers always used the Microsoft Ajax Library and did not generate JavaScript incrementally. You can revert to the previous behavior by setting unobtrusivejavascriptenabled to False in the appsettings section of the Web. config file.
Now, if you call Ajax.actionlink, the following markup will be generated:
<href= "/customajax/privacypolicy" onclick= " Sys.Mvc.AsyncHyperlink.handleClick (This, new Sys.UI.DomEvent (event), {InsertionMode:Sys.Mvc.InsertionMode.replace , Updatetargetid: ' privacy '}); " > Show Privacy Policy </a>
It does not use the Data-ajax tag property, but all metadata is placed in the onclick event. This also requires that you refer to the MicrosoftAjax.js and microsoftmvcajax.js scripts to make them work correctly. This also interrupts the progressive JavaScript principle because the method calls are included directly in the onclick tag attribute of the element.
If you are upgrading an earlier version of ASP. NET MVC, you may need this behavior in order to maintain backward compatibility. In all other cases, however, it is best to set unobtrusivejavascriptenabled to Ture, as it will form a cleaner tag and this is the future direction of Microsoft.
"NET MVC 4 Combat" Learning note 7:ajax (top)