Asp.net mvc 2中使用Ajax的三種方式
在Asp.net MVC中,我們能非常方便的使用Ajax。這篇文章將介紹三種Ajax使用的方式,分別為原始的Ajax調用、Jquery、Ajax Helper。分別采用這三種方式結合asp.net mvc去實現一個史上最簡單的留言板。
首先看一下原始的Ajax的調用的:
定義CommentController,代碼如下:
{
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方法。
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);
}
在View中引入此腳本,創建一個簡單的表單,并添加觸發的代碼:
<h4>Comments</h4>
<ul id="comments">
</ul>
<%= Html.TextArea("Comment", new{rows=5, cols=50}) %>
<button type="submit" onclick="getMessage()">Add Comment</button>
<span id="indicator" style="display:none"><img src="../../content/load.gif" alt="loading..." /></span>
</asp:Content>
<asp:Content ID="Content3" ContentPlaceHolderID="headContent" runat="server">
<script src="../../Scripts/custom_ajax.js" type="text/javascript"></script>
</asp:Content>
效果如下:
第二種方式:利用Jquery:
在控制器中添加代碼IndexJquery方法和AddComment方法的代碼,CommentController代碼如下所示:
{
private IList<string> _comments = new List<string>();
public ActionResult Index()
{
return View();
}
public ActionResult IndexJquery()
{
return View();
}
public ActionResult AddComment(string comment)
{
_comments.Add("<li>" + comment + "</li>");
return Content(string.Join("\n", _comments.ToArray()));
}
public void AddCommentServer()
{
string comment = Request["comment"].ToUpper();
_comments.Add("<li>" + comment + "</li>");
Response.ContentType = "text/html";
Response.Write(string.Join("\n", _comments.ToArray()));
}
}
根據IndexJquery,創建View表單IndexJquery.aspx:
<ul id="comments">
</ul>
<% using (Html.BeginForm("AddComment","Comment",FormMethod.Post,new {@class="hijax"})) { %>
<%= Html.TextArea("Comment", new{rows=5, cols=50}) %>
<button type="submit">Add Comment</button>
<span id="indicator" style="display:none"><img src="http://www.cnblogs.com/content/load.gif" alt="loading..." /></span>
<% } %>
在View中引用Jquery:<script src="http://www.cnblogs.com/Scripts/jquery-1.4.1.min.js" type="text/javascript">script>
添加下面腳本:
//execute when the DOM has been loaded
$(document).ready(function () {
//wire up to the form submit event
$("form.hijax").submit(function (event) {
event.preventDefault(); //prevent the actual form post
hijack(this, update_sessions, "html");
});
});
function hijack(form, callback, format) {
$("#indicator").show();
$.ajax({
url: form.action,
type: form.method,
dataType: format,
data: $(form).serialize(),
completed: $("#indicator").hide(),
success: callback
});
}
function update_sessions(result) {
//clear the form
$("form.hijax")[0].reset();
$("#comments").append(result);
}
</script>
效果:與方式一效果一樣。
第三種方式:Ajax Helper
將最簡單的留言板修改成Ajax Helper的方式。
1、首先了解一下Ajax Helper下面四種方法。
a、Ajax.ActionLink():它將渲染成一個超鏈接的標簽,類似于Html.ActionLink()。當它被點擊之后,將獲取新的內容并將它插入到HTML頁面中。
b、Ajax.BeginForm():它將渲染成一個HTML的Form表單,類似于Html.BeginForm()。當它提交之后,將獲取新的內容并將它插入到HTML頁面中。
c、Ajax.RouteLink():Ajax.RouteLink()類似于Ajax.ActionLink()。不過它可以根據任意的routing參數生成URL,不必包含調用的action。使用最多的場景是自定義的IController,里面沒有action。
d、Ajax.BeginRouteForm():同樣Ajax.BeginRouteForm()類似于Ajax.BeginForm()。這個Ajax等同于Html.RouteLink()。
這個例子中使用Ajax.BeginForm(),下面具體了解Ajax.BeginForm()的參數。看下面代碼:
{
HttpMethod = "POST",
UpdateTargetId = "comments",
InsertionMode = InsertionMode.InsertAfter
})) { %>
actionName: AddComment(action的名字)
controllerName:CommentController(Controller的名字)
ajaxOptions:
HttpMethod:Ajax的請求方式,這里為POST
UpdateTargetId :Ajax請求的結果顯示的標簽的ID,這里為comments
InsertionMode:將Ajax結果插入頁面的方式,這里將ajax的結果放置到comments的后面
2、實現:
在CommentController中添加IndexAjaxHelp方法。
{
return View();
}
根據IndexAjaxHelp生成View表單IndexAjaxHelp.aspx,定義表單:
<ul id="comments">
</ul>
<% using (Ajax.BeginForm("AddComment", new AjaxOptions
{
HttpMethod = "POST",
UpdateTargetId = "comments",
InsertionMode = InsertionMode.InsertAfter
})) { %>
<%= Html.TextArea("Comment", new{rows=5, cols=50}) %>
<button type="submit">Add Comment</button>
<% } %>
要在此View中添加下面兩個腳本文件:
<script src="http://www.cnblogs.com/Scripts/MicrosoftAjax.js" type="text/javascript">script>
<script src="http://www.cnblogs.com/Scripts/MicrosoftMvcAjax.js" type="text/javascript">script>
這樣就行了,我們發現比用Jquery方便很多,但是使用Jquery將靈活很多。
3、效果:和方式一樣。
總結:本文非常的簡單,在asp.net mvc中實現了3中ajax的調用方式,實現了一個最簡單的留言板程序。推薦使用Jquery和Ajax Helper這兩種。Ajax Helper使用非常簡單,Jquery比較靈活。
更新:三種方式都實現了一個最簡單的留言板程序
參考:
ASP.NET MVC 2 In Action
Pro ASP.NET MVC 2 Framework, Second Edition