Home / AJAX

Page History: How Do I Retrieve Data from a Page Method?

Compare Page Revisions



« Older Revision - Back to Page History - Newer Revision »


Page Revision: 2010/08/31 00:55


Problem

I have an ASP.NET WebForms page and I want to call an AJAX Page Method without using the ASP.NET AJAX libraries generated proxies using only jQuery.

Solution

Page methods are a special implementation of ASP.NET AJAX service callbacks that can be hosted inside of an ASP.NET WebForms page subclass. Page methods need to be static and like their full blown ASP.NET AJAX ASMX service counterparts take JSON POST input and return JSON result values. Page methods are a simplified way of making callbacks without separately setting up an ASMX or WCF Web Service.

Page Methods are simple RPC methods that take JSON POST data inputs and return a JSON encoded string of the result value from the method call and they can be readily called from jQuery AJAX calls from the client.

The input is a JSON object that contains one property for each parameter passed to the method, and the result returns a root object with a ‘d’ property that contains the actual result value. The reason for the ‘d’ property is security to avoid JSON execution attacks that can be run against JSON arrays.

Setting up a Page Method on the Server

Lets assume we have a simple form on the client with a textbox and a button to retrieve a simple HelloWorld message from the server. The idea is to enter your name, send it to the server and the server responds back with a HelloWorld message string. Here’s the base HTML to work with:

 
<div class="sample">
    <h3>Hello World with Page Methods</h3>
    <div class="containercontent">
        Enter your name: 
        <asp:TextBox runat="server" ID="txtName" Text="" />
        <input type="button" id="btnHelloWorld" value="Say Hello"  />
                
        <div id="divHelloMessage" class="errordisplay" style="display:none"></div>
    </div>
</div>

The whole simple UI including the callback message once retrieved looks like this: