JQuery

Calling custom ASP.NET http handlers with Ajax/JQuery


Ajax isn’t new, nor is it a single technology.  It’s a design approach for more efficient client / server communication.  Ajax is really a very simple concept that has changed the face of non media embedded websites (flash, silverlight).  Back in the ‘old days’ web pages where a purely one-way informational deal and user interaction was a pipe dream.  As website numbers grew, more focus was put on making the use of web sites a much richer and more interactive experience.  The technology vendors put efforts into boosting up their server side technology to allow the server to do most of the processing work so that even though the result was still rendered in HTML in the clients browser, we could now source data from databases on the server or other advanced processing could take place.  PHP, ASP.NET, Java Server Pages, Coldfusion, Perl are all examples of server side technologies.

Moving closer to where we are now, we do have great server side processing but our pages are still rendered in HTML, in full, in the browser and Javascript is used only to support an active loaded page and to run validation on forms and perform basic scripting again the browsers DOM (document object model). Each time something needed to change on a browser page, the client would need to re-requested the entire page from the server with the updated content.  Naff.

Client side – Calling the server

What the introduction of Ajax (Asynchronous JavaScript and XML) has allowed us to do is make cheeky background asynch calls to a server resource (asmx/config/aspx etc), pass it some data and receive a response without the need to reload the full page.  Essentially, using the javascript object XmlHttpRequest() a user is able to make the same type of call as is made when a page is requested, but behind the scenes on an already loaded page.  This also means that Javascript can handle the response from the call the server and change parts of the page dynamically.  In basic terms, we are making partial page changes using this magical XmlHttpRequest() object.

var xmlHttp = new XmlHttpRequest(); //This is the new way (from IE7 onward) for instantiating the object across all browsers (used to be an Active X Object in IE).

Once the object is instantiated, we assign the properties of the request to our new xmlHttp object properties. Namely:

1) query path as part of the url mypage?name=john&surname=smith

2) as a string send as part of the xmlhttprequest.send(string data) method

3) as xml as part of a string (concatenated XML tags)

4) as JSON, which is a delimited format for sending object data to the server {name:value,name:value} is a objects properties.

To make an ajax call, you create an instance of the Javascript XMLHttpRequest object, then using that object you set its properties and then call its Send method.

i) Set the HTTP method to obtain the data (GET or POST methods).

ii) Set the response handling method (the local client side Javascript method which will deal with the XmlHttp response)

iii) Optionally set the request header (the HTTP header info like Mime types etc)

iv) Set the location of the resource being requested (in our case our handler)

v) Call the XmlHttpRequest.Send() method and pass any string/xml/json data if required. Not required for our example.

Server side – Handling an ajax call

We now know how make our request from client Javascript.  Now we need to handle the request on the server.   This can be done by setting up a site that sits on IIS and serves the purpose of receiving and processing HTTP Requests from the client.  This happens all the time for your .asmx and .aspx pages in the form of http handlers which handle inbound requests to your IIS server.  For .aspx pages, IIS hands the client request off to the PageHandlerFactory http handler class and for your web services (.asmx) they are handled by the WebServiceHandlerFactory class (found in Web.Services.Protocols).  Therefore for a custom application, we can create our own http handler class and using the sites config file, we can specify a handler ‘extention’ to replace .aspx / .asmx etc that will force IIS to forward the inbound request to your custom handler class.

You can create one or more custom HTTP Handlers at the site level.  IIS receives the inbound http request, checks the path extention then using a lookup to the Web.Config file it can determine which ASP.NET type (or class) will be acting as the handler for this request.  Once the handler is deteremined, ASP.NET passes a  HTTPContext object (which is basically the .NET object representation of a HTTP Request) to the custom http handler which parses the request body and creates a HttpResponse object to send back to the client.

But why use a custom HTTP handler instead of a normal resource like an .aspx page? – Well, two simple reasons. They are less resource expensive (as the page as lots of events that fire like onLoad etc) and second you can wrap your request handler type (your class) into an assembly and move it around to any IIS server you want, update the web.config file and deploy.

To setup a custom handler, create a new web site on your IIS Server and in the root of the site, in the Web.Config file (add if not present), add/edit the following:

The path we set in the config (.myHttpHandler) is the location of where the HTTP Handler is listening for requests (indirectly as IIS handles the request first, but it is what will take care of processing the http request. It defines its address from the clients perspective.

Note also that the config file need to know the .NET Type that will process the request.  Ours is called ‘MyHttpRequestHandler’ is the code is shown below:

(Note that the IsReusable method is used to set whether the handler should stay resident in memory once called. Accepts a bool value.)

Now, by running an ajax call using the GET method to a url of either “mypage.myHttpHandler” (for local site) or http://server/mypage.myHttpHandler” if you are calling your custom HttpHandler from a remote server, IIS will handle the request, pass it to our custom handler and we will receive a response back to our set ajax response handler method.  An example use may be to send an XML or string request from the client using ajax, have the handler receive the payload (http request minus header) and process it and for the client side method to receive an xml response and process it as required (maybe to populate a list box for example).

Using JQuery for Ajax

JQuery is a single javascript file that makes programming the browser in JavaScript easier. Although you can buy big books on JQuery and that it appears to be a complex clientside programming language, its really not and is basically just a library, written in Javascript, of methods that abstracts away javascript code and simplifies common javascript operations.

JQuery is to Javascript what .NET is to the WinAPI. They both abstract away the details into simple to use methods.

Part of the JQuery library is a simplified way of calling a server location with ajax instead of doing it in javascript as per the above example. It is basically still a case of setting the server resource being requested, setting the method to handle the response etc but it is done with far less text and the creation of the HttpXmlRequest object is done for you.

You’ll notice that little information needs to be provided and you do not need to manually check with Javascript whether the response state is accepted. The JQuery handles that for you.  In our example, we are simply calling our customer http handler and are not passing any data.  The page ‘mypage’ does not need to exist as we are not calling a page handler, the only requirements is that the .myHttpHandler is the resource being requested.

Calling Web Services with ASP.NET AJAX

You may decide to deploy your supporting site logic in the form of web services.  Like custom HTTP Handlers, A Web Service can be consumed from an AJAX script and a response passed back to the specified response handling method.  This is very easily accomplished at Web Service design time and in fact visual studio comments this code out by default in the ASP.NET Web Service Application template.  The attribute class ScriptService (ensure you set a ‘using’ to System.Web.Script.Services) should prefix the class / service name and indicates to the ASP.NET AJAX Extensions that the web service can be consumed by a client side script.  On the Client Side, the ‘ScriptManager’ control is responsible for creating the client side proxy on page load.  The only caveat with this method is that calls cannot be made to a Web Service outside of the domain of which the client page resides… Security reasons. You can of course use the standard Javascript XMLHttpRequest object to make build and make SOAP calls from the client, but that’s a lot of messing about and makes the relationship a tightly coupled one (meaning the client needs to know a lot about the service and if the service changed, the client would need to be changed).

Summary

Ajax is a big part of web application programming these days.  Not only does it make standard web sites that render HTML from web servers much more interactive and greatly improves the user experience, but JQuery and AJAX can be used on any platform (e.g. Metastorm BPM and other BPM platforms that render HTML) that renders HTML from a hosting web server.  I have used IIS in this example to illustrate the use of .NET based http handlers, however you can create Java servlets that extend the Java http handler interface as well as PHP and the other service side technologies.

Advertisements