Tuesday, June 16, 2009

Using jQuery to directly call ASP.NET AJAX page methods

When it comes to lightweight client-side communication, I’ve noticed that many of you prefer ASP.NET AJAX’s page methods to full ASMX web services. In fact, page methods came up in the very first comment on my article about using jQuery to consume ASMX web services.

Given their popularity, I’d like to give them their due attention. As a result of Justin’s question in those comments, I discovered that you can call page methods via jQuery. In fact, it turns out that you can even do it without involving the ScriptManager at all.

In this post, I will clarify exactly what is and isn’t necessary in order to use page methods. Then, I’ll show you how to use jQuery to call a page method without using the ScriptManager.


Creating a page method for testing purposes.

Writing a page method is easy. They must be declared as static, and they must be decorated with the [WebMethod] attribute. Beyond that, ASP.NET AJAX takes care of the rest on the server side.

This will be our page method for the example:

public partial class _Default : Page  {   [WebMethod]   public static string GetDate()   {     return DateTime.Now.ToString();   } }

What about the ScriptManager and EnablePageMethods?

Traditionally, one of your first steps when utilizing page methods is to set the ScriptManager’s EnablePageMethods property to true.

Luckily, that property is a bit of a misnomer. It doesn’t enable page methods at all, but simply generates an inline JavaScript proxy for all of the appropriate methods in your page’s code-behind.

For example, if a ScriptManager is added to the above example’s corresponding Default.aspx and its EnablePageMethods property is set to true, this JavaScript will be injected into the page:

See full detail: http://encosia.com/2008/05/29/using-jquery-to-directly-call-aspnet-ajax-page-methods/

No comments: