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:var PageMethods = function() { PageMethods.initializeBase(this); this._timeout = 0; this._userContext = null; this._succeeded = null; this._failed = null; } PageMethods.prototype = { _get_path:function() { var p = this.get_path(); if (p) return p; else return PageMethods._staticInstance.get_path();}, GetDate:function(succeededCallback, failedCallback, userContext) { return this._invoke(this._get_path(), 'GetDate',false,{}, succeededCallback,failedCallback,userContext); }} PageMethods.registerClass('PageMethods',Sys.Net.WebServiceProxy); PageMethods._staticInstance = new PageMethods(); // Generic initialization code omitted for brevity. PageMethods.set_path("/jQuery-Page-Method/Default.aspx"); PageMethods.GetDate = function(onSuccess,onFailed,userContext) { PageMethods._staticInstance.GetDate(onSuccess,onFailed,userContext); }
Calling the page method with jQuery instead.
Knowing that a page method is consumed in the same way as a web service, consuming it with jQuery isn’t difficult. For more detailed information, see my previous article about making jQuery work with ASP.NET AJAX’s JSON serialized web services. Using the jQuery.ajax method, this is all there is to it:$.ajax({ type: "POST", url: "PageName.aspx/MethodName", beforeSend: function(xhr) { xhr.setRequestHeader("Content-type", "application/json; charset=utf-8"); }, dataType: "json", success: function(msg) { // Do something interesting here. } });
Putting it all together.
Corresponding to the example page method above, here’s our Default.aspx:Click here for the time.
$(document).ready(function() { // Add the page method call as an onclick handler for the div. $("#Result").click(function() { $.ajax({ type: "POST", url: "Default.aspx/GetDate", beforeSend: function(xhr) { xhr.setRequestHeader("Content-type", "application/json; charset=utf-8"); }, dataType: "json", success: function(msg) { // Replace the div's content with the page method's return. $("#Result").text(msg.d); } }); }); });