Close this search box.

ASP.NET AJAX callbacks to Web Methods in ASPX pages

Making ASP.NET AJAX calls to web services has become increasingly popular these days. This approach not only provides a good separation of concerns but also makes it possible to create a truly ajax’ed web site with JavaScript’s power on the client side. However, you may in some situations want to move one or more web methods to ASPX pages. You often have methods that are logically dedicated to specific ASPX pages, and you don’t really want them to be exposed to the public through the ASMX file. Generally, this is the most appealing reason why you want to place web methods in ASPX pages.

Both ASP.NET AJAX Extensions and ASP.NET 3.5 support AJAX callbacks to the web methods placed in ASPX pages. It only requires a few simple steps to do this. For example, you want to move a web method called GetProducts to an page named Products.aspx, and you want to invoke the GetProducts method directly from JavaScript. The first step is expose GetProducts as a web method.

 1: public partial class Products : System.Web.UI.Page 
   2: { 
   3: [System.Web.Services.WebMethod()] 
   4: [System.Web.Script.Services.ScriptMethod()] 
   5: public static List<Product> GetProducts(int cateogryID) 
   6: {
   7:   // Put your logic here to get the Product list 
   8: }

A few things to note here:

1. The method MUST be static

2. The method needs to be decorated with [WebMethod()]

3. The method needs to be decorated with [ScriptMethod()] if you want to make a ASP.NET AJAX callback to it

Next, remove the reference in the <Services> section of the ScriptManager tag and set the ScriptManager.EnablePageMethods property to true. This will make all the web methods on this page visible to the JavaScript client.

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

Finally, we need to change the JavaScript code to call the method through the PageMethods object instead of the Web Service.
  1: function GetProductsByCategoryID(categoryID)
   2: {
   3:     PageMethods.GetProducts(categoryID, OnGetProductsComplete);
   4: }
   6: function OnGetProductsComplete(result)
   7: {
   8:     // Put your logic here to display the result
   9: }
This article is part of the GWB Archives. Original Author: Frank Wang

Related Posts