.net 3.5 中的 伺服器端回調

來源:互聯網
上載者:User

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

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.