在aspx页面中,可能通过asp.net ajax调用其页面方法,具体设置如下。

1.服务器端代码(页面对象代码):

 
  
  1. using System.Web; 
  2. using System.Web.Services; 
  3. using System.Web.Script.Services; 
  4.  
  5. [ScriptService] 
  6. public partial class CallAspxMethod : System.Web.UI.Page 
  7.     [WebMethod] 
  8.     public static String Hello(String name) 
  9.     { 
  10.        return String.Format("Hello {0}", name); 
  11.     } 

其中,在页面对象类在添加ScriptService属性,在Hello方法上添加WebMethod属性,并且Hello方法必需为static静态方法。

2.前端DOM代码,将ScriptManager的EnablePageMethod属性值为True:

 
  
  1. <asp:ScriptManager ID="ScriptManagerDemo" runat="server"  
  2. EnablePageMethods="True"></asp:ScriptManager> 
  3. <input id="btnCallAspxMethod" type="button" value="CallAspxMethod"  
  4. onclick="return btnCallAspxMethod_onclick()" /> 

3.前端js代码:

 
  
  1. function btnCallAspxMethod_onclick() { 
  2. //PageMethods.Hello(name,onSuccess,onFailed,userContext);
  3.     PageMethods.Hello("彭金华", onSuccess); 
  4.  
  5. function onSuccess(result) 
  6.     alert(result); 

4.开始测试。

 

个人点评

i. 页面对象类的设置和调WebService的服务器端设置差不多,添加类属性ScriptService和方法属性WebMethod;

ii. 自动生成前端js代理对象PageMethods,组织本页面所有的WebMethod,并生成各自的js原型方法,如上述示例中的
PageMethods.Hello(name,onSuccess,onFailed,userContext);

iii. 自动生成的js原型方法,始终比服务器端方法要多三个参数onSuccess, onFailed和userContext,服务前端调用交互;

iv. 页面方法WebMothed必须为static静态的,在实际使用中,引起诸多不便。