淺析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創建Form
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
@ 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如下:
?1 2 3 4 5 6 7 8 9 |
<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" >
|
第二步:創建Ajax.BeginForm的new AjaxOptions()對象的Url指向的Action
?1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
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); //模擬處理數據需要的時間
//return View(model)會返回整個頁面,所以返回部分視圖。
return PartialView( "_RestaurantPatialView" , model);
}
return View(model);
}
|
註意:
關於使用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 參數指定的Id為restaurantList的html元素:
這裏在頁面中添加:id為restaurantList的<div>:
?1 2 |
<div id= "restaurantList" >...
</div>
|
第四步:(可選)為增強用戶體驗,添加AjaxOption對象的LoadingElementId參數指定的Id為loding的html元素:
1 2 3 4 5 6 |
new AjaxOptions()
{
....
LoadingElementId = "loding" ,
LoadingElementDuration = 2000
}))
|
這裏在頁面中添加:id為loding的元素,添加了包含一個動態的刷新圖片<div>:
cshtml文件中添加:
?1 2 3 |
<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創建超鏈接
?1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
@[email protected](item.Name, "Details" , "Reviews" , new {id = item.Id}, new [email protected] = "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 [email protected]= "isStar" })
}
|
對應生成的最終html為:
?1 2 3 4 5 6 7 8 |
<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" >
|
第二步:定義出來響應超鏈接的Action:
?1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
/// <summary>
///關於使用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元素:
?1 2 3 |
<div id= "renderBody" >
....
</div>
|
第四步:(可選)為增強用戶體驗,添加AjaxOptionsd對象的LoadingElementId參數指定的Id為loding的html元素:
與1.1第四步相同。
二、手工打造自己的“非介入式”Javascript”
第一步:添加表單:
?1 2 3 4 5 6 7 8 9 10 11 |
@* ---------------------------------------------------------
需要手工為Form添加些屬性標簽,用於錨點
模仿MVC框架的構建自己的“非介入式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為:
?1 2 3 4 5 |
<form data-otf-ajax-updatetarget= "#restaurantList"
data-otf-ajax= "true"
action= "/Reviews"
method= "post"
novalidate= "novalidate" >
|
第二步:添加處理表單的Action:
這裏與1.1的第二步一樣。
第三步:添加Js處理表單:
?1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
$( 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而已。
如對本文有疑問,請提交到交流社區,廣大熱心網友會為你解答!! 點擊進入社區
您可能感興趣的文章:
- jQuery使用ajaxSubmit()提交表單示例
- jquery中ajax使用error調試錯誤的方法
- 基於jquery的$.ajax async使用
- jquery.ajax之beforeSend方法使用介紹
- 使用jquery的ajax需要註意的地方dataType的設置
- jquery序列化form表單使用ajax提交後處理返回的json數據
- 跨域請求之jQuery的ajax jsonp的使用解惑
- Ajax的使用代碼解析
- Ajax的使用四大步驟
- AJAX的使用方法詳解
- http://www.jb51.net/article/72660.htm
淺析Asp.net MVC 中Ajax的使用