JQuery, AJAX, JSON, and .NET

Client rich features often require some dabbling across a couple of different technologies in order to produce your desired product. JavaScript alongside some type of server technology is usually the course of action. My recent work involved the use of ASP.NET 3.5.1. Web service calls and parsing is a very monotonous and tedious task in pure native JavaScript, however, with a couple of tools and know-how, this type of work becomes a pleasure rather than a pain.

So, in this demonstration, we will use JQuery (a JavaScript Library) to make an AJAX call passing JSON from the client to a .NET web service.

JQuery

If you haven’t used it, you have never really lived! JQuery makes writing JavaScript a pleasure. It offers much, much more than I can cover here obviously. We will focus on the a single “ajax” portion of this library.  Download and details at: http://jquery.com/

JSON

Passing around a bunch of XML and making standard web service requests is a little tedious at times. That is where JSON (JavaScript Object Notation) comes in. It is much more readable in its serialized form, and reduces payload size substantially. JSON is a type of notation, however there is a library we will use called JSON2 that will provide simple functionality to serialize and deserialize JSON according to standards. Download and details at: http://www.json.org/js.html

Download Visual Studio Solution Example

1. In a solution in Visual Studio, create a new item type of “Web Service.” In this example, it is simply called “Webservice.amx”.

2. We will be using scripts to call this web service and will need to uncomment (or add) the following ScriptService tag to the web service class:

[System.Web.Script.Services.ScriptService]

3. Now I can create a standard method to complete some type of functionality. Here is the class code of my example:

Capture4
In my example you will notice that I return a List of a strongly typed object. This list will be automatically parsed to JSON by .NET (in .NET 3.5.1) as long as the content type is specified correctly by the client. The parameters for this method are present to demonstrate two things: First deserializing a JSON object sent to the server, and secondly receiving a standard integer parameter.

4. Okay, now we need to create a client. Add a new .aspx page (or html or whatever).

5. Import both your scripts onto your page. For example you should something like the following lines to import JSON2.js and jquery-1.4.2.min.js:

Capture2

6. I created some mock HTML elements to allow for user action (to initiate the request). Basically just an input button that we capture the click event of. And a place to dump our results retrieved by the server.

Capture3

7. Now we need to add the JavaScript. Here it all is:

Capture1

So let’s break down what is going on here, since this is really where it all gets pieced together.
This script describes, whenever our button is clicked, initiate an Ajax call to a web service where it passes two parameters in JSON format, and receives a JSON object list. So the first thing is the creation of the JavaScript object that will be serialized. This gets deserialized server side and must match the exact same properties of a server object called “NameValue”.  Here are some explanations of the properties used in our AJAX Call:
URL: This should be a relative path from your page on where to find the web service and the also the name of the method within the web service to call specifically.

contentType: This specifies the content type of what is being sent from the Client to the Server for the parameters.

Data: This is the actual data that is being sent to the server. This needs to be stringified into JSON if your content type is set as JSON.

dataType: This specifies the type of data that gets returned from the web service to the client. Again, should by ‘json’.

Success: The event to call on success. Has one argument that contains the return value (in our case a JSON object).
Error: the event to call on failure of the web service call.

And thats it. Now you have a working AJAX call to a .NET Web service. However, there is one final gotcha you should be aware of. When trying to access the webservice outside of your development environment, in other words, when deploying a solution, you will have to add a configuration node to your web.config in order to expose it for remote use.

8. Add the following node into your web.config file inside the <system.web> node:

Capture5
This will allow GET and POST requests. Just remove either one of not using that type of protocol.

Some Additional Notes:

The “DATA” of the AJAX Call:

data: JSON.stringify({ nameValue: JSON.stringify(nameValue), test: 4 }),

This can be confusing. First off, we serialize the data parameters as a whole, since this is what the DATA TYPE as a whole is configured to be (rather than XML). So this is a standard when using JSON content type.  Secondly, we stringify another object into json (yes, inside the first stringifiy command). This is because you’ll notice in the webservice method, I’m expecting a string (which I parse manually into an object).

The “Success”  function:

success: function(msg)

The function always returns a single variable. And in this variable your strongly typed object (already parsed from JSON) will be ready to go by accessing “.d” i.e. msg.d

*Note: I have never been able to get the web service call to reliably work while specifying a different contentType from dataType…hence use JSON for everything or nothing in this example scenario. If you have any suggestions or comments on this, please let me know.