日期:2014-05-16  浏览次数:20620 次

8.1Ajax类库介绍
在ASP.NET MVC中使用
-Microsoft ASP.NET Ajax
-jQuery


Ajax的使用范围
-适合Ajax的场景
-不适合Ajax的场景
  Ajax软肋:
    不保存Http状态,没有回退,状态保留
    不支持JavaScript脚本
    Ajax成瘾症


Ajax使用实例
-每个Ajax请求都会制定确定的Action
-Action会判断是否来自Ajax
-针对Ajax请求必须返回一个特殊的View

脚本启用问题
<%using (Ajax.BeginForm(“HelloAjax”,
new AjaxOptions{ UpdateTargetId= “results” }))
{ %>
<%= Html.TextBox(“query”, null, new {size=40}) %>
<input type=”submit” />
<%} %>
<div id=”results”></div>

<script src=”/Scripts/MicrosoftAjax.js” type=”text/javascript”></script>
<script src=”/Scripts/MicrosoftMvcAjax.js” type=”text/javascript”></script>

写在低下,页面先加载后加载脚本
加载是阻塞模式,后加载脚本好  //小技巧

Action
public string HelloAjax(string query)
{
return “You entered: “ + query;

}


<form action="/Home/HelloAjax" method="post"
onsubmit=”Sys.Mvc.AsyncForm.handleSubmit(this, new Sys.UI.DomEvent(event),
{ insertionMode: Sys.Mvc.InsertionMode.replace,
updateTargetId:'result'});">
js禁用咋办?

解决脚本启用问题
x-requested-with: XMLHttpRequest
query=Hello%20Ajax!&X-Requested-With=XMLHttpRequest

检查是否有x-requested-with

public ActionResultHelloAjax(string query)
{
//确认请求来自于ajax
string isAjaxPost= Request.Form[“X-Requested-With”] ??
Request.Headers[“X-Requested-With”];
if (!String.IsNullOrEmpty(isAjaxPost))
{return Content(“You entered: “ + query);} //ajax
return RedirectToAction(“Index”, new { query = query }); //http请求
}}
//有魔术字[“X-Requested-With”] ,应该用函数封装

//make sure this is an Asynchpost
if (Request.IsAjaxRequest())// 这是微软自带的
{
return Content(“You entered: “ + query);
}
else
{
return RedirectToAction(“Index”, new { query = query });
}
}

使用PrtialView返回
[<%if(ViewData.Model.Count>0){ %>
<table cellpadding=”5”>
<tr><td><b>Product</b></td>
<td><b>Price</b></td></tr>
<%foreach(MVCAjax.Models.Productp in ViewData.Model)
{ %>
<tr><td><%= Html.Encode(p.ProductName) %></td>
<td><%= p.UnitPrice%></td></tr>
<%} %>
</table>
<%} %>

PartialView返回
IList<Product> products = new List<Product>();
if(!String.IsNullOrEmpty(query)){
NorthwindDataContextdb= new NorthwindDataContext();
varproducts = from p in db.Products
where p.ProductName.StartsWith(query)
select p).ToList();
}
if(Request.IsAjaxRequest())
{return View(“ProductSearchResults”, products);
}else{
return View(products);
}
<div id=”results”><%Html.RenderPartial(“ProductSearchResults”, ViewData.Model); %></div>


2011-4-22 23:54 danny