淺析Asp.net MVC 中Ajax的使用
一、使用System.Web.Mvc.Ajax
1.1 System.Web.Mvc.Ajax.BeginForm
1.2 System.Web.Mvc.Ajax.ActionLink
二、手工打造自己的“非介入式”Javascript”
一、使用System.Web.Mvc.Ajax

1.1 System.Web.Mvc.Ajax.BeginForm
第一步:用Ajax.BeginForm創(chuàng)建Form
@using (Ajax.BeginForm(
new AjaxOptions()
{
HttpMethod = "post",
Url = @Url.Action("Index","Reviews"),
InsertionMode = InsertionMode.Replace,
UpdateTargetId = "restaurantList",
LoadingElementId = "loding",
LoadingElementDuration = 2000
}))
{
<input type="search" name="searchItem"/>
<input type="submit" value="按名稱搜索"/>
}
最終生成的form如下:
<form id="form0" method="post"
data-ajax-url="/Reviews"
data-ajax-update="#restaurantList"
data-ajax-mode="replace"
data-ajax-method="post"
data-ajax-loading-duration="2000"
data-ajax-loading="#loding"
data-ajax="true"
action="/Reviews" novalidate="novalidate">
第二步:創(chuàng)建Ajax.BeginForm的new AjaxOptions()對象的Url指向的Action
new AjaxOptions()
{
...
Url = @Url.Action("Index","Reviews")
...
}
public ActionResult Index(string searchKey = null)
{
var model = _restaurantReviews.Where(r => searchKey == null || r.Name.ToLower().Contains(searchKey.ToLower().Trim()))
.OrderByDescending(r => r.Rating)
.Take(100)
.Select(r=>new RestaurantReview()
{
City = r.City,
Country = r.Country,
Id = r.Id,
Name = r.Name,
Rating = r.Rating
}).ToList();
if (Request.IsAjaxRequest())
{
System.Threading.Thread.Sleep(1000 * 3);//模擬處理數(shù)據(jù)需要的時間
//return View(model)會返回整個頁面,所以返回部分視圖。
return PartialView("_RestaurantPatialView", model);
}
return View(model);
}
注意:
關(guān)于使用System.Web.Mvc.Ajax的說明:
Controller的Action方法:
(1)當顯式添加[HttpPost],傳給System.Web.Mvc.Ajax的AjaxOptions()的HttpMethod只能為 "post",
(2)當顯式添加[HttpGet],傳給System.Web.Mvc.Ajax的AjaxOptions()的HttpMethod只能為 "get",
(3)當都沒有顯式添加[HttpPost]和[HttpGet],傳給System.Web.Mvc.Ajax的AjaxOptions()的HttpMethod可以為 "get"也可以為"post",
第三步:添加要承載更新頁面的html元素,
也就是添加添加AjaxOptionsd對象的UpdateTargetId 參數(shù)指定的Id為restaurantList的html元素:
這里在頁面中添加:id為restaurantList的<div>:
<div id="restaurantList">... </div>
第四步:(可選)為增強用戶體驗,添加AjaxOption對象的LoadingElementId參數(shù)指定的Id為loding的html元素:
new AjaxOptions()
{
....
LoadingElementId = "loding",
LoadingElementDuration = 2000
}))
這里在頁面中添加:id為loding的元素,添加了包含一個動態(tài)的刷新圖片<div>:

cshtml文件中添加:
<div id="loding" hidden="hidden">
<img class="smallLoadingImg" src="@Url.Content("~/Content/images/loading.gif")" />
</div>
1.2 System.Web.Mvc.Ajax.ActionLink
System.Web.Mvc.Ajax.ActionLink與System.Web.Mvc.Ajax.BeginForm用法基本一致
第一步:使用System.Web.Mvc.Ajax.ActionLink創(chuàng)建超鏈接
@*@Html.ActionLink(item.Name, "Details", "Reviews",new{id = item.Id},new {@class ="isStar"})*@
@*<a class="isStar" href="@Url.Action("Details","Reviews", new {id = item.Id})">@item.Name</a>*@
@*使用Ajax的超鏈接*@
@{
var ajaxOptions = new AjaxOptions()
{
HttpMethod = "post",
//Url = @Url.Action(""),
UpdateTargetId = "renderBody",
InsertionMode = InsertionMode.Replace,
LoadingElementId = "loding",
LoadingElementDuration = 2000
};
@Ajax.ActionLink(item.Name, "Details", "Reviews", new { id = item.Id }, ajaxOptions, new {@class="isStar"})
}
對應(yīng)生成的最終html為:
<a class="isStar" href="/Reviews/Details/1" data-ajax-update="#renderBody" data-ajax-mode="replace" data-ajax-method="post" data-ajax-loading-duration="2000" data-ajax-loading="#loding" data-ajax="true">
第二步:定義出來響應(yīng)超鏈接的Action:
/// <summary>
///關(guān)于使用System.Web.Mvc.Ajax的說明:
/// Controller的Action方法:
/// (1)當顯式添加[HttpPost],傳給System.Web.Mvc.Ajax的AjaxOptions()的HttpMethod只能為 "post",
/// (2)當顯式添加[HttpGet],傳給System.Web.Mvc.Ajax的AjaxOptions()的HttpMethod只能為 "get",
/// (3) 當都沒有顯式添加[HttpPost]和[HttpGet],傳給System.Web.Mvc.Ajax的AjaxOptions()的HttpMethod可以為 "get"也可以為"post",
/// </summary>
/// <param name="id"></param>
/// <returns></returns>
public ActionResult Details(int id=1)
{
var model = (from r in _restaurantReviews
where r.Id == id
select r).FirstOrDefault();
if (Request.IsAjaxRequest())
{
return PartialView("_RestaurantDetails", model);
}
return View(model);
}
第三步:定義承載更新部分的html元素:
<div id="renderBody">
....
</div>
第四步:(可選)為增強用戶體驗,添加AjaxOptionsd對象的LoadingElementId參數(shù)指定的Id為loding的html元素:
與1.1第四步相同。
二、手工打造自己的“非介入式”Javascript”
第一步:添加表單:
@* ---------------------------------------------------------
需要手工為Form添加些屬性標簽,用于錨點
模仿MVC框架的構(gòu)建自己的“非介入式Javascript”模式
-------------------------------------------------------*@
<form method="post"
action="@Url.Action("Index")"
data-otf-ajax="true"
data-otf-ajax-updatetarget="#restaurantList">
<input type="search" name="searchItem" />
<input type="submit" value="按名稱搜索" />
</form>
生成的form為:
<form data-otf-ajax-updatetarget="#restaurantList"
data-otf-ajax="true"
action="/Reviews"
method="post"
novalidate="novalidate">
第二步:添加處理表單的Action:
這里與1.1的第二步一樣。
第三步:添加Js處理表單:
$(function () {
var ajaxFormSubmit = function() {
var $form = $(this);
var ajaxOption = {
type: $form.attr("method"),
url: $form.attr("action"),
data: $form.serialize()
};
$.ajax(ajaxOption).done(function(data) {
var updateTarget = $form.attr("data-otf-ajax-updatetarget");
var $updateTarget = $(updateTarget);
if ($updateTarget.length > 0) {
var $returnHtml = $(data);
$updateTarget.empty().append(data);
$returnHtml.effect("highlight");
}
});
return false;
};
$("form[data-otf-ajax='true']").submit(ajaxFormSubmit);
});
注意:
所謂的“非介入式Javascript”模式,是指假如沒有添加這一步,表單照樣能被處理,只是沒用到Ajax而已。
相關(guān)文章
jquery訪問servlet并返回數(shù)據(jù)到頁面的方法
這篇文章主要介紹了jquery訪問servlet并返回數(shù)據(jù)到頁面的方法,實例分析了jQuery操作servlet實現(xiàn)Ajax的技巧,具有一定參考借鑒價值,需要的朋友可以參考下2015-02-02
無限分級和tree結(jié)構(gòu)數(shù)據(jù)增刪改【附DEMO下載】
這篇文章主要介紹了無限分級和tree結(jié)構(gòu)數(shù)據(jù)增刪改的相關(guān)資料,需要的朋友可以參考下2016-05-05
IIS7中Ajax.AjaxMethod無效的原因及解決方法
使用Ajax.AjaxMethod方法在asp.net的服務(wù)器下一切正常,用iis的時候,js中總是cs類找不到,具體的解決方法如下,遇到類似情況的朋友可以參考下2013-07-07

