天天看點

一起談.NET技術,Asp.net mvc 2中使用Ajax的三種方式

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

    在View中引入此腳本,建立一個簡單的表單,并添加觸發的代碼:

<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">

<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="http://www.cnblogs.com/content/load.gif" alt="loading..." /></span>

</asp:Content>

<asp:Content ID="Content3" ContentPlaceHolderID="headContent" runat="server">

<script src="http://www.cnblogs.com/Scripts/custom_ajax.js" type="text/javascript"></script>

   效果如下:

一起談.NET技術,Asp.net mvc 2中使用Ajax的三種方式

     第二種方式:利用Jquery:

     在控制器中添加代碼IndexJquery方法和AddComment方法的代碼,CommentController代碼如下所示:

public ActionResult IndexJquery()

public ActionResult AddComment(string comment)

return Content(string.Join("\n", _comments.ToArray()));

     根據IndexJquery,建立View表單IndexJquery.aspx:

<% using (Html.BeginForm("AddComment","Comment",FormMethod.Post,new {@class="hijax"})) { %>

<button type="submit">Add Comment</button>

<% } %>

    在View中引用Jquery:<script src="http://www.cnblogs.com/Scripts/jquery-1.4.1.min.js" type="text/javascript">script>

  添加下面腳本:

<a href="http://11011.net/software/vspaste"></a>

&lt;script type="text/javascript"&gt;

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

&lt;/script&gt;

  效果:與方式一效果一樣。

   第三種方式: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()的參數。看下面代碼:

&lt;% using (Ajax.BeginForm("AddComment", new AjaxOptions

HttpMethod = "POST",

UpdateTargetId = "comments",

InsertionMode = InsertionMode.InsertAfter

})) { %&gt;

    actionName: AddComment(action的名字)

    controllerName:CommentController(Controller的名字)

    ajaxOptions:

         HttpMethod:Ajax的請求方式,這裡為POST

         UpdateTargetId :Ajax請求的結果顯示的标簽的ID,這裡為comments

         InsertionMode:将Ajax結果插入頁面的方式,這裡将ajax的結果放置到comments的後面

   2、實作:

   在CommentController中添加IndexAjaxHelp方法。

public ActionResult IndexAjaxHelp()

    根據IndexAjaxHelp生成View表單IndexAjaxHelp.aspx,定義表單:

    要在此View中添加下面兩個腳本檔案:

    &lt;script src="http://www.cnblogs.com/Scripts/MicrosoftAjax.js" type="text/javascript"&gt;script&gt;

    &lt;script src="http://www.cnblogs.com/Scripts/MicrosoftMvcAjax.js" type="text/javascript"&gt;script&gt;

   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

繼續閱讀