Wahlin on .NET

Creating and Consuming ASP.NET AJAX Page Methods

Using Page Methods when adding the ScriptService attribute is overkill for a single page -- find out how to add the functionality directly using AJAX.

Web services provide a great way to exchange data between ASP.NET AJAX pages and a server using lightweight JSON messages (see my previous articles for examples of integrating Web services into ASP.NET AJAX applications). However, creating a separate .ASMX Web service file and adding the ScriptService attribute to the service class may feel like overkill in situations where a single page consumes the service's methods. In some cases, it's more convenient to simply add the functionality provided by the Web service directly into an ASP.NET code-beside page. In these cases, ASP.NET AJAX page methods can be used instead of Web Services.

Page methods are static/shared (depending on your language) methods added into an ASP.NET page's code-beside file. They're normal methods, although they must have the WebService attribute applied to them to work properly. Page methods communicate directly with an ASP.NET AJAX-enabled page and pass JSON request and response messages back and forth, just as WebMethods do in Web services.

The code below shows an example of an ASP.NET code-beside page that contains two page methods named, respectively, GetCustomer() and Add(). Both methods are marked as shared since VB.NET is used and are decorated with the WebMethod attribute.

Partial Class _Default
   Inherits System.Web.UI.Page

   <WebMethod()> _
   Public Shared Function _
      GetCustomer(ByVal id _
      As String) As Customer
      'Simulate hitting database to 
      'get customer
      Dim cust As New Customer()
      cust.CustomerID = id
      cust.FirstName = "John"
      cust.LastName = "Doe"
      cust.Country = "USA"
      Return cust
   End Function

   <WebMethod()> _
   Public Shared Function Add( _
      ByVal x As Integer, _
      ByVal y As Integer) _
      As Integer
      Return x + y
   End Function
End Class

Looking through the code above you can see that creating page methods is no different than creating any other type of method once you know that they must be static/shared and have the WebMethod attribute applied. However, how do you access page methods from an ASP.NET AJAX page without performing a normal postback operation?

With Web services, you use the ScriptManager's Services property to define the path to the .ASMX service file. Adding a reference to one or more services automatically causes the ScriptManager to generate a client-side proxy class. Making AJAX calls to page methods is even easier than making Web service calls, although it still involves the ScriptManager. Access to page methods is disabled by default so you must set the ScriptManager control's EnablePageMethods property to true, as shown here:

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

By setting EnablePageMethods to true, the ScriptManager will automatically generate JavaScript proxy code that is capable of calling the page methods in the code-beside page. However, the name of the proxy isn't based on the namespace and class names as with Web services. Instead, the proxy is accessed on the client-side through a special class generated by the ScriptManager called PageMethods.

The code below shows an example of calling the two methods shown earlier and handling the data they return. Note that each method is accessed from the client-side by using the PageMethods proxy class. When calling a method from the client-side, you'll pass the parameters the method takes as well as the callback method that should be called when the appropriate page method returns data. Each callback method accepts a result parameter that contains the returned data.

<script type="text/javascript">
   function Add()
   {
      var x = $get("txtX").value;
      var y = $get("txtY").value;
      PageMethods.Add(x,y,OnWSAdd);
   }
  
   function OnWSAdd(result)
   {
      $get( 
         "spanAddResult").innerHTML +
         = result;
   }

   function GetCustomer()
   {
      var id = 
      $get("txtCustomerID").value;
      PageMethods.GetCustomer(
         id,OnWSGetCustomer);
   }

   function OnWSGetCustomer(result)
   {
      $get(
      "spanCustomerResult").innerHTML 
      = result.FirstName + " " + 
      result.LastName;
   }
</script>

While Web Services are more appropriate when multiple pages need to consume a service, page methods provide a simple way to add Web service-style functionality directly into an ASP.NET code-beside page. By using them, you can minimize the number of files that have to be deployed once an application moves to production.

About the Author

Dan Wahlin (Microsoft MVP for ASP.NET and XML Web Services) is the founder of The Wahlin Group which specializes in .NET and SharePoint onsite, online and video training and consulting solutions. Dan also founded the XML for ASP.NET Developers Web site, which focuses on using ASP.NET, XML, AJAX, Silverlight and Web Services in Microsoft's .NET platform. He's also on the INETA Speaker's Bureau and speaks at conferences and user groups around the world. Dan has written several books on .NET including "Professional Silverlight 2 for ASP.NET Developers," "Professional ASP.NET 3.5 AJAX, ASP.NET 2.0 MVP Hacks and Tips," and "XML for ASP.NET Developers." Read Dan's blog here.

comments powered by Disqus

Featured

  • Compare New GitHub Copilot Free Plan for Visual Studio/VS Code to Paid Plans

    The free plan restricts the number of completions, chat requests and access to AI models, being suitable for occasional users and small projects.

  • Diving Deep into .NET MAUI

    Ever since someone figured out that fiddling bits results in source code, developers have sought one codebase for all types of apps on all platforms, with Microsoft's latest attempt to further that effort being .NET MAUI.

  • Copilot AI Boosts Abound in New VS Code v1.96

    Microsoft improved on its new "Copilot Edit" functionality in the latest release of Visual Studio Code, v1.96, its open-source based code editor that has become the most popular in the world according to many surveys.

  • AdaBoost Regression Using C#

    Dr. James McCaffrey from Microsoft Research presents a complete end-to-end demonstration of the AdaBoost.R2 algorithm for regression problems (where the goal is to predict a single numeric value). The implementation follows the original source research paper closely, so you can use it as a guide for customization for specific scenarios.

  • Versioning and Documenting ASP.NET Core Services

    Building an API with ASP.NET Core is only half the job. If your API is going to live more than one release cycle, you're going to need to version it. If you have other people building clients for it, you're going to need to document it.

Subscribe on YouTube