Frank Wang's inspirations on .NET

IEnumerable<Inspiration> inspirations = from i in DataContext.Inspirations where i.Sharable == true select i

ASP.NET AJAX callbacks to Web Methods in ASPX pages

Thursday, March 13, 2008 10:39 PM

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: }
   5:  
   6: function OnGetProductsComplete(result)
   7: {
   8:     // Put your logic here to display the result
   9: }

Feedback

# re: ASP.NET AJAX callbacks to Web Methods in ASPX pages

Thanks for the write up! Thats money! 3/23/2008 10:25 PM | Chuck Conway

# re: ASP.NET AJAX callbacks to Web Methods in ASPX pages

Very good! Thanks for the information! 8/26/2008 4:49 PM | Diego Gazotto Dezembro

# re: ASP.NET AJAX callbacks to Web Methods in ASPX pages

interesting.. is this a good design if you wanted to make an ajaxified server control or would ICallbackEventHandler be better? 10/5/2008 6:17 AM | Drew

Post a comment





 

Please add 2 and 6 and type the answer here: