Home | Projects | Tutorials | Articles | live chat | Submit Project | Big Vote
 
Ajax Projects
.NET Frameworks
Java Frameworks
PHP Frameworks
Ruby Frameworks
Other Frameworks
Cool AJAX sites
Ajax Resources
Ajax Tools
JavaScript frameworks

 Home /  Tutorials / ASP.NET MVC and JSON

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.

Read The Full Tutorial.
































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.
view plaincopy to clipboardprint?

   1. public class Car { 
   2.     public string Name { get; set; } 
   3.     public string Color { get; set; } 
   4. } 

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.


view plaincopy to clipboardprint?

   1. public class CarsController : Controller 
   2. { 
   3.     public JsonResult GetCars() 
   4.     { 
   5.         List<Car> cars = Cars.GetCars(); 
   6.         return this.Json(cars); 
   7.     } 
   8. } 

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:
view plaincopy to clipboardprint?

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

[{"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.
view plaincopy to clipboardprint?

   1. function getRequestObject() { 
   2.     var req = false; 
   3.     if(window.XMLHttpRequest) { 
   4.         req = new XMLHttpRequest(); 
   5.     } else if(window.ActiveXObject) { 
   6.         req = new ActiveXObject("Microsoft.XMLHTTP"); 
   7.     } 
   8.     return req; 
   9. } 

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.


view plaincopy to clipboardprint?

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

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.
view plaincopy to clipboardprint?

   1. function handleResponse() { 
   2.     if (request.readyState == 4) { 
   3.         var cars = eval('(' + request.responseText + ')'); 
   4.  
   5.         for each(car in cars) { 
   6.             alert(car.Name + ', ' + car.Color); 
   7.         } 
   8.     } 
   9. } 

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.
view plaincopy to clipboardprint?

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

$.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.

source: svennerberg

AddThis Social Bookmark Button
Top Projects
MessengerFX
MSN Web Messenger
ebuddy
e-messenger
ILoveIM
You Tube
AJAX file upload
KoolIM.com
Meebo
Ajax.NET Professional
Tutorials
Demystifying AJAX and Creating ASP.NET AJAX Applications using VS2008
Ajax Beginners Tutorial
Communicate with Flash
Integrating ASP.NET AJAX with SharePoint
ASP.NET MVC Action Filter - Ajax Only Attribute
[PHP, AJAX, MySQL] Simple AJAX chat in PHP
PHP and Dojo Sending and Receiving Form Data
Loading content with jQuery AJAX - selecting the element to inject
Declarative Syntax for Widgets
Facebook Beacon JavaScript