ASP.NET Ajax中PageMethod的运用

1.    使用PageMehtod的步骤。

 

a)     启用ASP.NET Ajax,关于如何启用ASP.NET Ajax这里不作叙述;

b)     Web.Config中添加HttpModule: ScriptModule;

<httpModules>
<add name="ScriptModule" type="System.Web.Handlers.ScriptModule, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/>
</httpModules>

c)     WebFormCode behind添加WebMethod方法,注意是publicstatic和方法的Attribute;

[System.Web.Services.WebMethod]
public static String GetDateTimeNow()
  {
    
return System.DateTime.Now.ToString();
  }

d)     在相应客户端代码中编写调用Server方法及处理返回结果的两个function

function QButton1_onclick()
  {
    PageMethods.GetDateTimeNow(showResult);
  }
function showResult(result)
  {
     alert(result);
  }

e)     WebForm上的ScriptManager添加属性EnablePageMethods="True";

 

<asp:ScriptManager EnablePageMethods="true"  ID="ScriptManage" runat="server" />

2.    关于参数传递。

 

使用PageMethods调用的方法如下:

PageMethods.[MethodName](parameter1, parameter2, …, SuccessMethod, FailedMethod, userContext);

其中

Parameter?为与Server端一一对应的参数.

SuccessMethod,必需,WebMethod正确返回时的回调函数,原型为onSuccess(result).

FailedMethod,非必需,WebMethod出错返回时的回调函数,原形为onFailed(error).

 注意:

SuccessMethod 和 FailedMethod方法可以添加可选参数 userContext 和 methodName 参数

如 :onSuccess(result, userContext,methodName)

       onFailed(error, userContext,methodName)

       userContext参数:用户调用PageMethods时添加的自定义数据。

       methodName参数:用户调用Server端的方法名。

 

3.    返回值及出错处理。

返回值的获取:

SuccessMethod第一个参数为Server方法返回值.

出错处理:

可能通过提供FailedMethod处理Server抛出的异常, FailedMethod的第一个参数为Server端异常对应的客户端对象,可以通过error.get_message()获取异常信息.

posted @ 2010-03-01 17:07  年轻的蜗牛  阅读(971)  评论(0编辑  收藏  举报