Learning notes for ASP. net mvc 4 Practice 7: Ajax (I ),

Source: Internet
Author: User
Tags actionlink

Learning notes for ASP. net mvc 4 Practice 7: Ajax (I ),

I. Ajax of jQuery:

1. Use jQuery to form Ajax requests:

1) Create an AjaxExamples project and add the CustomAjax controller:

namespace AjaxExamples.Controllers{    public class CustomAjaxController : Controller    {        public ActionResult Index()        {            return View();        }        public ActionResult PrivacyPolicy()        {            return PartialView();        }    }}

2) Add the custom jQuery code:

$(document).ready(function () {    $('#privacyLink').click(function (event) {        event.preventDefault();        var url = $(this).attr('href');        $('#privacy').load(url);    });});

3) add some views of PrivacyPolicy:

<H2> the confidentiality policy 

4) Add the Index View:

@ Html. actionLink ("show confidentiality policy", "PrivacyPolicy", null, new {id = "privacyLink "}) <div id = "privacy"> </div> <script type = "text/javascript" src = "@ Url. content ("~ /Scripts/jquery-1.10.2.min.js ")"> </script> @ * by default, the layout view has introduced jQuery. However, an error is reported during running, so introduce * @ <script type = "text/javascript" src = "@ Url again. content ("~ /Scripts/AjaxDemo. js ")"> </script>

If you disable javascript, the above page will be redirected to the PrivacyPolicy page. However, the PrivacyPolicy action returns partial views, which is not beautiful. To solve this problem, you can modify the PrivacyPolicy action:

Public ActionResult PrivacyPolicy () {if (Request. IsAjaxRequest () // check whether Ajax call {return PartialView () ;}return View ();}

2. Use Ajax to submit form data:

1) Introduce AddComment action:

Namespace AjaxExamples. controllers {public class CustomAjaxController: Controller {private static List <string> _ comments = new List <string> (); // Save the comments List public ActionResult Index () {return View (_ comments);} public ActionResult PrivacyPolicy () {if (Request. isAjaxRequest () // check whether Ajax call {return PartialView ();} return View ();} [HttpPost] public ActionResult AddComment (string comment) {_ comments. add (comment); // Save the new comment if (Request. isAjaxRequest () {ViewBag. comment = comment; return PartialView (); // send the Comment to the view} return RedirectToAction ("Index ");}}}

2) add some views of AddComment:

<li>@ViewBag.Comment</li>

3) modify the Index View:

@ Model IEnumerable <string> <ul id = "comments"> @ foreach (var comment in Model) {<li >@comment </li >}</ul> @ using (Html. beginForm ("AddComment", "CustomAjax", formediahod. post, new {id = "commentForm"}) {@ Html. textArea ("Comment", new {rows = 5, cols = 50 }) <br/> <input type = "submit" value = "Add Comment"/>}< script type = "text/javascript" src = "@ Url. content ("~ /Scripts/jquery-1.10.2.min.js ")"> </script> @ * by default, the layout view has introduced jQuery. However, an error is reported during running, so introduce * @ <script type = "text/javascript" src = "@ Url again. content ("~ /Scripts/AjaxDemo. js ")"> </script>

4) Modify AjaxDemo. js:

$ (Document ). ready (function () {$ ('# commentForm '). submit (function (event) {event. preventDefault (); var data = $ (this ). serialize (); // serialize the form into a string var url =$ (this ). attr ('action'); $. post (url, data, function (response) {$ ('# comments '). append (response); // append the result to the comment list });});});

Ii. Ajax helper for ASP. net mvc:

1. Ajax. ActionLink:

1) Add jquery. unobtrusive-ajax.js to the project: Enter Install-Package Microsoft. jQuery. Unobtrusive. Ajax-version 3.0.0 in the Program Manager Console

2) modify the Index View:

@ Ajax. actionLink ("show confidentiality policy", "PrivacyPolicy", new AjaxOptions {InsertionMode = InsertionMode. replace, UpdateTargetId = "privacy"}) <div id = "privacy"> </div> <script type = "text/javascript" src = "@ Url. content ("~ /Scripts/jquery-1.10.2.min.js ")"> </script> @ * by default, the layout view has introduced jQuery. However, an error is reported during running, so introduce * @ <script type = "text/javascript" src = "@ Url again. content ("~ /Scripts/jquery. unobtrusive-ajax.min.js ")"> </script>

Start debugging and view the HTML generated on the page as follows:

<A data-ajax = "true" data-ajax-mode = "replace" data-ajax-update = "# privacy" href = "/CustomAjax/PrivacyPolicy"> display confidentiality policies </a>

The data-ajax tag attribute is used to indicate the asynchronous execution of hyperlinks. data-ajax-mode and data-ajax-update correspond to the AjaxOptions object.

When a page is loaded, the script in jquery. unobtrusive-ajax finds all links with the data-ajax tag attribute and attaches a click event. Similarly, if the browser disables javascript, the link functions as a normal hyperlink.

2. Ajax. BeginForm:

Modify the Index View:

<Ul id = "comments"> </ul> @ using (Ajax. beginForm ("AddComment", new AjaxOptions {UpdateTargetId = "comments", InsertionMode = InsertionMode. insertAfter}) {@ Html. textArea ("Comment", new {rows = 5, cols = 50 }) <br/> <input type = "submit" value = "Add Comment"/>}< script type = "text/javascript" src = "@ Url. content ("~ /Scripts/jquery-1.10.2.min.js ")"> </script> @ * by default, the layout view has introduced jQuery. However, an error is reported during running, so introduce * @ <script type = "text/javascript" src = "@ Url again. content ("~ /Scripts/jquery. unobtrusive-ajax.min.js ")"> </script>

3. Ajax options:

4. Differences with earlier versions of ASP. net mvc:

Although the Ajax helper has been a part of ASP. net mvc since the first version, jQuery is now the default. In earlier versions of the framework, these guides always use Microsoft's Ajax library and do not generate javascript incrementally. You can set UnobtrusiveJavaScriptEnabled to false in the AppSettings section of the web. config file to restore the previous behavior.

Now, if Ajax. ActionLink is called, the following tag is generated:

<A href = "/CustomAjax/PrivacyPolicy" onclick = "Sys. mvc. asyncHyperlink. handleClick (this, new Sys. UI. domEvent (event), {insertionMode: Sys. mvc. insertionMode. replace, updateTargetId: 'privacy '}); "> display confidentiality policies </a>

It does not use the data-ajax label attribute, but all metadata is stored in the onclick event. This also requires that you reference the MicrosoftAjax. js and MicrosoftMvcAjax. js scripts to make them work normally. Because the onclick label attribute of an element directly contains a method call, this also interrupts the progressive javascript principle.

If you are upgrading an ASP. net mvc website in earlier versions, you may need this behavior to maintain backward compatibility. However, in all other cases, it is best to set UnobtrusiveJavaScriptEnabled to true, because it will form a more clean mark and this is also the future direction of Microsoft.

Source code download password: cv8w

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