Analysis on the use of Ajax in Asp.net MVC and mvcajax

Source: Internet
Author: User
Tags actionlink

Analysis on the use of Ajax in Asp.net MVC and mvcajax

1. Use System. Web. Mvc. Ajax

1.1 System. Web. Mvc. Ajax. BeginForm

1.2 System. Web. Mvc. Ajax. ActionLink

2. manually create your own "non-invasive" Javascript"

1. Use System. Web. Mvc. Ajax

 

1.1 System. Web. Mvc. Ajax. BeginForm

Step 1: Use Ajax. BeginForm to create a Form

@ Using (Ajax. beginForm (new AjaxOptions () {HttpMethod = "post", Url = @ Url. action ("Index", "Reviews"), InsertionMode = InsertionMode. replace, UpdateTargetId = "restaurantList", LoadingElementId = "loding", LoadingElementDuration = 2000 })) {<input type = "search" name = "searchItem"/> <input type = "submit" value = "search by name"/>}

The final generated form is as follows:

 <form id="form0" method="post"     data-ajax-url="/Reviews"    data-ajax-update="#restaurantList"    data-ajax-mode="replace"    data-ajax-method="post"    data-ajax-loading-duration="2000"    data-ajax-loading="#loding"    data-ajax="true"    action="/Reviews" novalidate="novalidate">

Step 2: Create the Action to which the Url of the new AjaxOptions () object of Ajax. BeginForm points

New AjaxOptions (){... url = @ Url. action ("Index", "Reviews ")...} public ActionResult Index (string searchKey = null) {var model = _ Your antreviews. where (r => searchKey = null | r. name. toLower (). contains (searchKey. toLower (). trim ())). orderByDescending (r => r. rating ). take (1, 100 ). select (r => new RestaurantReview () {City = r. city, Country = r. country, Id = r. id, Name = r. name, Rating = r. rating }) . ToList (); if (Request. isAjaxRequest () {System. threading. thread. sleep (1000*3); // time required to simulate Data Processing // return View (model) returns the entire page, so some views are returned. Return PartialView ("_ RestaurantPatialView", model);} return View (model );}

Note:

Instructions on using System. Web. Mvc. Ajax:

Controller Action method:

(1) When [HttpPost] is explicitly added, the HttpMethod passed to AjaxOptions () of System. Web. Mvc. Ajax can only be "post ",

(2) When you explicitly add [HttpGet], the HttpMethod passed to AjaxOptions () of System. Web. Mvc. Ajax can only be "get ",

(3) When neither [HttpPost] nor [HttpGet] is explicitly added, it is passed to System. web. mvc. the HttpMethod of Ajax AjaxOptions () can be "get" or "post ",

Step 3: add the html element to carry the Update page,

That is to say, add the html element with the Id specified by the UpdateTargetId parameter of the AjaxOptionsd object as the restaurantList:

Add <div>:

<div id="restaurantList">...</div>

Step 4: (optional) Add the html element with the Id loding specified by the LoadingElementId parameter of the AjaxOption object to enhance the user experience:

  new AjaxOptions()    {      ....      LoadingElementId = "loding",      LoadingElementDuration = 2000    }))

Here we add the loding element on the page, which includes a Dynamic Refresh image <div>:

Add the following content to the cshtml file:

<div id="loding" hidden="hidden">  </div>

1.2 System. Web. Mvc. Ajax. ActionLink

The usage of System. Web. Mvc. Ajax. ActionLink is basically the same as that of System. Web. Mvc. Ajax. BeginForm.

Step 1: Use System. Web. Mvc. Ajax. ActionLink to create a hyperlink

@ * @ Html. actionLink (item. name, "Details", "Reviews", new {id = item. id}, new {@ class = "isStar"}) * @ * <a class = "isStar" href = "@ Url. action ("Details", "Reviews", new {id = item. id}) "> @ item. name </a> * @ * use the Ajax hyperlink * @ {var ajaxOptions = new AjaxOptions () {HttpMethod = "post", // Url = @ Url. action (""), UpdateTargetId = "renderBody", InsertionMode = InsertionMode. replace, LoadingElementId = "loding", LoadingElementDuration = 2000}; @ Ajax. actionLink (item. name, "Details", "Reviews", new {id = item. id}, ajaxOptions, new {@ class = "isStar "})}

The final html generated is:

<a class="isStar"   href="/Reviews/Details/1"   data-ajax-update="#renderBody"   data-ajax-mode="replace"   data-ajax-method="post"   data-ajax-loading-duration="2000"   data-ajax-loading="#loding"   data-ajax="true">

Step 2: Define the Action for responding to the hyperlink:

/// <Summary> /// about using System. web. mvc. ajax Description: // Controller Action Method: // (1) when [HttpPost] is explicitly added, it is passed to System. web. mvc. the HttpMethod of Ajax AjaxOptions () can only be "post", // (2) When [HttpGet] is explicitly added, it is passed to System. web. mvc. the HttpMethod of Ajax AjaxOptions () can only be "get", // (3) when neither [HttpPost] nor [HttpGet] is explicitly added, it is passed to System. web. mvc. the HttpMethod of Ajax AjaxOptions () can be "get" or "post ", /// </summary> /// <param name = "id"> </param> /// <returns> </returns> public ActionResult Details (int id = 1) {var model = (from r in _ Your antreviews where r. id = id select r ). firstOrDefault (); if (Request. isAjaxRequest () {return PartialView ("_ Your antdetails", model);} return View (model );}

Step 3: Define the html elements that carry the updated part:

   <div id="renderBody">             ....             </div>   

Step 4: (optional) to enhance user experience, add the html element with the Id specified by LoadingElementId of the AjaxOptionsd object as loding:

This is the same as step 4 of step 2.

2. manually create your own "non-invasive" Javascript"

Step 1: Add a form:

@ * ----------------------------------------------------------- Manually add some attribute labels for the Form, it is used for the anchor to simulate the MVC framework and build your own "non-invasive Javascript" Mode ----------------------------------------------- * @ <form method = "post" action = "@ Url. action ("Index ") "data-otf-ajax =" true "data-otf-ajax-updatetarget =" # restaurantList "> <input type =" search "name =" searchItem "/> <input type = "submit" value = "search by name"/> </form>

The generated form is:

<form data-otf-ajax-updatetarget="#restaurantList"      data-otf-ajax="true"      action="/Reviews"      method="post"      novalidate="novalidate">

Step 2: add the Action for processing the form:

This is the same as the second step of Step 1.1.

Step 3: Add a Js Processing Form:

$(function () {  var ajaxFormSubmit = function() {    var $form = $(this);    var ajaxOption = {      type: $form.attr("method"),      url: $form.attr("action"),      data: $form.serialize()    };    $.ajax(ajaxOption).done(function(data) {      var updateTarget = $form.attr("data-otf-ajax-updatetarget");      var $updateTarget = $(updateTarget);      if ($updateTarget.length > 0) {        var $returnHtml = $(data);        $updateTarget.empty().append(data);        $returnHtml.effect("highlight");      }          });    return false;  };  $("form[data-otf-ajax='true']").submit(ajaxFormSubmit);});

Note:

The so-called "non-invasive Javascript" Mode means that if this step is not added, the form can still be processed, but Ajax is not used.

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.