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:
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: