您的位置:首页 > 编程语言 > ASP

AJAX调用aspx的静态方法(二)

2009-05-05 23:05 190 查看
上次的文章中说到在页面中异步调用WebServices中的方法,当然也可以异步调用aspx.cs中的静态方法。看下MSDN上的示例代码

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="CallAspxStaticMethod.aspx.cs" Inherits="CallAspxStaticMethod" %>

2

3<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

4

5<html xmlns="http://www.w3.org/1999/xhtml">

6<head runat="server">

7 <title>Using Page Methods with Session State</title>

8 <style type="text/css">

9 </style>

15</head>

16<body>

17 <form id="form1" runat="server">

18 <asp:ScriptManager ID="ScriptManager1"

19 runat="server" EnablePageMethods="true">

20 <Scripts>

21 <asp:ScriptReference Path="JS/PageMethods.js"/>

22 </Scripts>

23 </asp:ScriptManager>

24 </form>

25

26 <center>

27 <table>

28 <tr align="left">

29 <td>Write current date and time in session state:</td>

30 <td>

31 <input type="button"

32 onclick="SetSessionValue('SessionValue', Date())"

33 value="Write" />

34 </td>

35 </tr>

36 <tr align="left">

37 <td>Read current date and time from session state:</td>

38 <td>

39 <input type="button"

40 onclick="GetSessionValue('SessionValue')"

41 value="Read" />

42 </td>

43 </tr>

44 </table>

45 </center>

46

47 <hr/>

48

49 <span style="background-color:Aqua" id="ResultId"></span>

50</body>

51</html>

52
在上面的代码中要注意一点,一定要将ScriptManager的EnablePageMethods属性设为true,这样才可以调用aspx.cs中的方法,ScriptManager下的ScriptReference属性是下面为异步调用写好的js函数

using System;

2using System.Collections.Generic;

3using System.Linq;

4using System.Web;

5using System.Web.UI;

6using System.Web.UI.WebControls;

7using System.Web.Services;

8

9public partial class CallAspxStaticMethod : System.Web.UI.Page

10
在两个静态方法中要加上[WebMethod]属性。这样才可以被客户端js异步调用.

// PageMethods.js

2

3var displayElement;

4

5// Initializes global variables and session state.

6

12// Gets the session state value.

13

18//Sets the session state value.

19

24// Callback function invoked on successful

25// completion of the page method.

26

33// Callback function invoked on failure

34// of the page method.

35

42if (typeof (Sys) !== "undefined") Sys.Application.notifyScriptLoaded();
GetSessionValue()方法中都有一个PageMethods.GetSessionValue方法,这个方法对应着服务器端的GetSessionValue方法。浏览页面后,我们可以在html源文件中看到关于PageMethods对象的定义.
<script type="text/javascript">

2//<![CDATA[

3PageMethods.registerClass('PageMethods',Sys.Net.WebServiceProxy);

29PageMethods._staticInstance = new PageMethods();

30PageMethods.set_path("/Ajax/CallAspxStaticMethod.aspx");

56//]]>

70</script>

71
在这里我们可以看到GetSessionValue:function(key,succeededCallback, failedCallback, userContext) 函数,在PageMethods.js中给他传入了相应的回调函数。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: