In usability we trust

UX and all things web

ASP.NET MVC and JSON

In the AJAX community, JSON have become the preferred way of sending and receiving data. That’s not surprising since it’s lightweight, fast and easy to understand. Also, since it’s a subset of Javascript, it’s familiar territory for Javascript coders.

In the ASP.NET MVC Framework, passing JSON from the server to the client script is almost too easy. In this article I will walk you through the code required to make it work.

The back end

Suppose we have a class named Cars like the one below. We want to feed our web page with a list of cars that we want to display AJAX style, preferably by sending the list as a JSON object.

public class Car {
public string Name { get; set; }
public string Color { get; set; }
}

With the ASP.NET MVC Framework it’s a breeze. In your Controller you simply create a method of the type JsonResult which returns a JSON object. You then use the Json() method to transform the class to JSON.

public class CarsController : Controller
{
public JsonResult GetCars()
{
List<Car> cars = Cars.GetCars();
return this.Json(cars);
}
}

Calling this method will return JSON that looks something like this:

[{"Name":"Saab","Color":"Red"},{"Name":"Volvo","Color":"Blue"}]

Making the AJAX call

To get the list of cars on the client side, you want to make an AJAX call to the Controller method GetCars(). This is done by calling the URL /Cars/GetCars/.

First I’ll walk you through how to do it with pure Javascript. Then I’ll show you how to do it with the jQuery library.

The Classic Javascript way

First of all you have to create an instance of the XMLHttpRequest object. It’s through this object that you communicate with the back end. Since IE 6 doesn’t support this object but do have support for an ActiveX object that essentially does the same thing, we initially have to do some checking to make sure that we use the correct object. I’ve created a wrapper function that with the help of object detection determines which object to use and then returns it.

function getRequestObject() {
var req = false;
if(window.XMLHttpRequest) {
req = new XMLHttpRequest();
} else if(window.ActiveXObject) {
req = new ActiveXObject("Microsoft.XMLHTTP");
}
return req;
}

I use the getRequestObject function to get the correct Request Object and then gets on with setting up the request.

var request = getRequestObject();
request.onreadystatechange = handleResponse;
request.open('GET', '/Cars/GetCars', true);
request.send(null);

Note: If you’re unfamiliar with AJAX and find this code really strange, I recommend that you read getting started with AJAX from Mozilla Developer Center.

Ok, so the AJAX Call is all set up. The last thing to do is to create the function handleResponse that takes care of the request and the received data.

function handleResponse() {
if (request.readyState == 4) {
var cars = eval('(' + request.responseText + ')');

for each(car in cars) {
alert(car.Name + ', ' + car.Color);
}
}
}

The object is received as JSON text through the responseText property of the request object. To convert it to a JSON object you can use the Eval() function. It will parse the text and produce an object structure. This is a fast and convenient way of doing it, but be aware of that it has potential security issues. Only use it if you know that you can trust the source. Otherwise you should use a more robust JSON parser.

The code in this example will throw an alert for each item in the JSON object and display it’s properties. This is done by looping through the received object. Notice how we can access the properties of the object through convenient dot notation.

The jQuery way

The client side scripting is even easier using jQuery. All the Javascript code above can be replaced with this.

$.getJSON("/Cars/GetCars", null, function(data) {
$.each(data, function(index, car) {
alert(car.Name, car.Color)
});
});

jQuery handles everything that happens in the background, like instantiating the request object and parsing the received JSON object. So it does all the heavy lifting and leaves the fun stuff to you, like doing creative things with the received data.

Note: For brevity I have excluded all error handling in this example. This should naturally always be considered in a live application.

1 Comment

  1. The jQuery way, I think there is a mistake, because the code doesn’t work for me..

Leave a Reply to gadget Cancel reply

Your email address will not be published.

*