Three ways to use Ajax in ASP.net MVC 2

Source: Internet
Author: User

In asp.net mvc, we can use Ajax very conveniently. This article will introduce the three ways Ajax uses, respectively, for the original Ajax invocation, Jquery, and Ajax Helper. These three methods are combined with asp.net mvc to achieve the simplest walls in history.

First look at the original Ajax invocation of the

Define Commentcontroller, code as follows:

public class CommentController : Controller
{
   private IList<string> _comments = new List<string>();

   public ActionResult Index()
   {
     return View();
   }

   public void AddCommentServer()
   {
      string comment = Request["comment"].ToUpper();
     _comments.Add("<li>" + comment + "</li>");
     Response.ContentType = "text/html";
     Response.Write(string.Join("\n", _comments.ToArray()));
   }

}

Add a custom_ajax.js to asp.net mvc and join the following scripting code using AJAX to invoke the Addcommentserver method.

function Getxmlhttprequest () {
var xhr;
Check for IE implementation (s)
if (typeof ActiveXObject!= ' undefined ') {
try {
XHR = new ActiveXObject ("Msxml2.xmlhttp");
catch (e) {
XHR = new ActiveXObject ("Microsoft.XMLHTTP");
}
else if (XMLHttpRequest) {
This works for Firefox, Safari, Opera
XHR = new XMLHttpRequest ();
} else {
Alert ("Sorry, your browser does not support Ajax");
}

return XHR;
}

function GetMessage () {
Get we XML HTTP request object
var xhr = Getxmlhttprequest ();

Prepare the request
Xhr.open ("Get", "comment/addcommentserver?comment=" + document.getElementById ("Comment"). Value, True

Setup the callback function
Xhr.onreadystatechange = function () {
ReadyState 4 means we ' re done
if (xhr.readystate!= 4) return;

Populate the page with the result
document.getElementById (' comments '). InnerHTML = document.getElementById (' comments '). InnerHTML + Xhr.responsetext;
};

Fire our Request
Xhr.send (NULL);
}

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.