Implementing AJAX in ASP.NET

Setting up the Page

We are now ready to start coding. Create a new page, or open an existing one and in the code behind file, add the following code in the Page_Load event:

VB.NET

Public Class Index
  Inherits System.Web.UI.Page
  Private Sub Page_Load(sender As Object, e As EventArgs) Handles MyBase.Load
    Ajax.Utility.RegisterTypeForAjax(GetType(Index))
  '...
  End Sub
  '...
End Class

C#

public class Index : System.Web.UI.Page{
  private void Page_Load(object sender, EventArgs e){
      Ajax.Utility.RegisterTypeForAjax(typeof(Index));     
      //...   
  }
  //... 
}

The call to RegisterTypeForAjax emits the following JavaScript on the page (alternatively, you could manually place the following two lines on the page):

<script language="javascript" src="ajax/common.ashx"></script>
<script language="javascript"
src="ajax/Namespace.PageClass,AssemblyName.ashx"></script>

Where the bolded parts have the following meaning:

  • Namespace.PageClass - The namespace and class of the current page (this will typically be the value of the Inherits attribute in the @Page directive)
  • AssemblyName - The name of the assembly the current page is part of (this will typically be the name of your project)

Bellow is a sample output for the sample.aspx page in an AjaxPlay project:

<%@ Page Inherits="AjaxPlay.Sample" Codebehind="sample.aspx.cs" ... %>
<html>
<head>
  <script language="javascript" src="ajax/common.ashx"></script>
  <script language="javascript"
          src="ajax/AjaxPlay.Sample,AjaxPlay.ashx"></script>
</head>
  <body>   
    <form id="Form1" method="post" runat="server">
      ...
    </form>   
  </body>
</html>

You can test that everything is working properly by manually navigating to the src paths in your browser (view source and copy and paste the paths). If both paths output some (seemingly) meaningless text, you’ve done well so far. If they’re outputting nothing or ASP.NET errors, something was improperly done.

Even if you don’t know how HttpHandlers work, the above should be understandable. Via the web.config, we’ve made sure that all requests that go to ajax/*.ashx are processed by the custom handler. Obviously, the two script tags will be processed by this custom handler.

Creating the Server-Side Functions

We’ll now create a server-side function that’ll be asynchronously be available from a client-side call. Since not all return types are currently supported (don’t worry, upcoming versions will build on what’s currently there), we’ll stick with our simple ServerSideAdd functionality. In the code behind file, add the following method to your page class:

VB.NET

<Ajax.AjaxMethod()> _
Public Function ServerSideAdd (byval firstNumber As Integer, byval secondNumber
                                                As Integer) As Integer
Return firstNumber + secondNumber
End Function

C#

[Ajax.AjaxMethod()]
public int ServerSideAdd(int firstNumber, int secondNumber)
{
  return firstNumber + secondNumber;
}

Note that the functions have the Ajax.AjaxMethod attribute set. The attribute serves to tell that wrapper to create JavaScript proxies for these methods so that they might be called client-side.

Making our client-side call

The last step is to call the function using JavaScript. The AJAX wrapper took care of creating a JavaScript function called Sample.ServerSideAdd function which takes two parameters. For the most basic functionality, all we need to do is call the method and pass two numbers:

<%@ Page Inherits="AjaxPlay.Sample" Codebehind="sample.aspx.cs" ... %>
<html>
<head>
  <script language="javascript" src="ajax/common.ashx"></script>
  <script language="javascript"
          src="ajax/AjaxPlay.Sample,AjaxPlay.ashx"></script>
</head>
  <body>   
    <form id="Form1" method="post" runat="server">
      <script language="javascript">
        var response = Sample.ServerSideAdd(100,99);
        alert(response.value);
      </script>
    </form>   
  </body>
</html>

Of course, we’ll want to use this powerful capability for more than simply alerting the user. That’s why all client-side proxies (such as the JavaScript Sample.ServerSideAdd function), also accept an additional property. The property is the callback function called in order to process the response:

Sample.ServerSideAdd(100,99, ServerSideAdd_CallBack);

function ServerSideAdd_CallBack(response){
 if (response.error != null){
  alert(response.error);
  return;
 }
 alert(response.value);
}

We can see from the above code that we’ve specified an extra parameter. ServerSideAdd_CallBack (also shown above) is the client-side function used to process the response from the server. The callback function receives a response object which exposes three key properties:

  • value - the actual return value (be it a string, custom object or dataset) of the server-side function.
  • error - an error message, if any.
  • request - the raw response from the xml http request.
  • context - a context object.

First we check the error value to see if any errors occurred. You can easily play with the error property by throwing an exception in the server-side function. Then, in this simplified case, we alert the value. The request property can be used to get additional information (see box bellow).

To learn more about the Xml Http request, check out this link dump.

You might also like...

Comments

Contribute

Why not write for us? Or you could submit an event or a user group in your area. Alternatively just tell us what you think!

Our tools

We've got automatic conversion tools to convert C# to VB.NET, VB.NET to C#. Also you can compress javascript and compress css and generate sql connection strings.

“Measuring programming progress by lines of code is like measuring aircraft building progress by weight.” - Bill Gates