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);
}