在Asp.net MVC中,我们能非常方便的使用Ajax。这篇文章将介绍三种Ajax使用的方式,分别为原始的Ajax调用、Jquery、Ajax Helper。分别采用这三种方式结合asp.net mvc去实现一个史上最简单的留言板。
首先看一下原始的Ajax的调用的
定义CommentController,代码如下:
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()));
}
}
在Asp.net MVC中添加一个custom_ajax.js,加入下面使用ajax的脚本代码,调用AddCommentServer方法。
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("对不起,你的浏览器不支持ajax");
}
return xhr;
}
function getMessage() {
//get our 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);
}