Think In Geek

In geek we trust

Creating and consuming JSON data in MVC 2

Recently I started working in a project using MVC 2. I found out a very useful feature to retrieve JSON data from the server using an Action in a Controller.

This feature is in the base Controller class, which we inherit when we create a new controller. If you take a look into the different methods this class has you’ll find those ones:

// Summary:
//     Creates a System.Web.Mvc.JsonResult object that serializes the specified
//     object to JavaScript Object Notation (JSON).
// Parameters:
//   data:
//     The JavaScript object graph to serialize.
// Returns:
//     The JSON result object that serializes the specified object to JSON format.
//     The result object that is prepared by this method is written to the response
//     by the MVC framework when the object is executed.
protected internal JsonResult Json(object data);

Along with this method, there are some overloads that allow more parameters, you can see them all in here: Controller.Json Method. In this example I’ll use the first one, which is the simplest.

This method returns a JsonResult, which inherits from ActionResult. This means that the result from a Json call can be returned in any controller action, as you would normally return a View. To use this method, you simply have to call it and pass it an object. The controller will be smart enough to inspect the object and create a valid JSON string containing all the info from the original object. Here’s a little example:

public ActionResult GetPersonInfo(int id)
	//For this example we don't get the person info from any data layer
    var jsonData = new
        GeneralInfo = new
            Name = "John",
            Surname = "AppleSeed"
        AddressInfo = new
            Street = "Infinite Loop, 1",
            Phone = "555-1111"
    return Json(jsonData);

This will have an action on the controller which will return us JSON data ready to be consumed by our javascript code in the view. To see how a client view would look like, consuming this data, here’s a little example using jQuery:

    async: false,
    url: '/ControllerName/GetPersonInfo/' + id,
    type: 'POST',
    success: function (data) {
        //data here is the JSON data
       //use it however you like
Share on FacebookShare on Google+Tweet about this on TwitterShare on LinkedIn

, , ,

Leave a Reply

Your email address will not be published. Required fields are marked *