.net 3.5 中的 服务器端回调

   .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  为客户端异步调用指定回调函数,在回调函数中接收返回值并进一步处理。

  1. .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>

原文地址:https://www.cnblogs.com/hbb0b0/p/1885111.html