.net 2.0 中我們可以實現ICallbackContainer 介面進行伺服器端回調,但是這種方法需要在服務端手工構造在黏合用戶端與服務端js代碼,用戶端需要編寫回調完成的
處理方法,整個寫起來有點羅嗦。在.net 3.5中提供了更為簡潔的回調方法。
想要使用ASP.NET AJAX在用戶端JavaScript中非同步呼叫定義在ASP.NET頁面中的方法,需要的條件:
1 伺服器端方法聲明為公有(public);
2 伺服器端方法聲明為類方法(C#中的static,VB.NET中的Shared),而不是執行個體方法;
3 伺服器端方法添加[WebMethod]屬性;
4 將頁面中ScriptManager控制項的EnablePageMethods屬性設定為true;
5 在用戶端使用如下JavaScript文法調用該頁面方法:
PageMethods.[MethodName](param1, param2,..., callbackFunction);
6 為用戶端非同步呼叫指定回呼函數,在回呼函數中接收傳回值並進一步處理。
- .cs 檔案中的代碼
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace AJAXTest
{
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
//1 .方法必須公用是靜態方法
//2 .添加WebMethod特性
[System.Web.Services.WebMethod]
public static List<String> GetResult()
{
List<string> myList = new List<string>();
int i = 0;
do
{
myList.Add(i.ToString());
i++;
} while (i < 10);
return myList;
}
[System.Web.Services.WebMethod]
public static int Add(int p1,int p2)
{
return p1 + p2;
}
}
}
2.
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="AJAXTest._Default" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title></title>
<script type="text/javascript">
function callBack(result) {
//debugger;
alert("Success:"+result );
}
function callBackError(result) {
alert("Error:"+result );
}
function callServer() {
//debugger;
PageMethods.GetResult(callBack, callBack);
}
function callServerAdd() {
//debugger;
//1 通過 PageMethods調用 服務端標識的方法
//2 [WebMethod](參數1,參數2,調用成功後的回呼函數,發生異常的回呼函數)
PageMethods.Add(3,5, callBack,callBackError);
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
//設定EnablePageMethods=true
<asp:ScriptManager ID="ScriptManager1" EnablePageMethods="true" runat="server">
</asp:ScriptManager>
<input value="Test" type="button" onclick="callServer()" />
<input value="Add" type="button" onclick="callServerAdd()" />
</div>
</form>
</body>
</html>