LA.NET [EN]

Mar 03

The MVC framework: returning JSON

Posted in ASP.NET JQuery MVC      Comments Off on The MVC framework: returning JSON

After a few days without talking about ASP.NET MVC, it’s time to resume my study of the platform. Today we’re going to look at a special ActionResult type: the JsonResult class. You can use this specific ActionResult type for returning JSON from a controller’s action method. This class offers three public properties:

  • ContentEncoding: as you can suspect, you can pass an Encoding object that should be used for encoding the response returned from the server;
  • ContentType: used for specifying the content type of the current response (btw, you’ll get application/json as you might expect);
  • Data: user for passing the object that should be serialized and returned back to the client.

There’s really an important *internal* detail you should know when  you use this action result type: internally, it uses the JavaScriptSerializer class to serialize the object passed to the Data property of the class. This is important (especially if you’re returning dates from the server,as you’ll see in the example I’ll be presenting at the end of the post) and might force you to use the client Sys.Serialization.JavaScriptSerializer class for recovering the object that was serialized on the server side.

Lets take a look at a quick and simple example that shows how to use this action result type. We’re going to start by building an action method that returns the current time from the server. I’ve chosen this simple example so that I could point out some caveats regarding the use of this specific action result type. Here’s how the GetTime method looks like:

public ActionResult GetTime() {
   return Json( DateTime.Now );
}

Nothing could be simpler, right? Now, in order to get this from our view, we’re going to perform a GET call and we’re going to use JQuery to simplify the code we need to write in order to interact with the server (do keep in mind that you could use several approaches to invoke this controller method from the client side). We’ll start by adding the necessary JS files:

<script type="text/javascript" src=”<%= Url.Content( "~/Scripts/jquery-1.2.6.js"  ) %>”>
</script>
<script type="text/javascript" src=”<%= Url.Content( "~/Scripts/MicrosoftAjax.debug.js"  ) %>”>
</script>

We’re using the Url.Content method to get the correct url for the scripts based on the context of the current request. I’m also adding the MS ajax client file and you’ll see why in a minute (btw, do notice that I’m using the debug versions of these files. In a real world app, you’d really would want to use the minified versions of these files). Now, I’ll just add an anchor and some JS code for hooking up the click event: when a user clicks on the link,I’m going to perform my AJAX call and get the JSON with the current date from the server. Here’s that code:

<a href="#" id="loader">Get time</a>
<script type="text/javascript">
        $(function() {
          $("#loader").click(function() {
            $.get(
                  ”<%= Url.Action( "GetTime","Home" ) %>”,
                  null,
                  function(time) { alert(time); var t = Sys.Serialization.JavaScriptSerializer.deserialize(time); alert(t); }, "");
          });
        });
</script>

Some interesting observations:

I’m using the Url.Action to get the url for the controller’s method I want to invoke;

I’m using the JQuery get method to perform the ajax call. There were other options here…for instance, you might be tempted to use the getJSON method. Unfortunately, the getJSON method won’t work because it automatically tries to deserialize the returned data (which then gets passed to the callback method) and that won’t work here (due to the fact that there isn’t a standard way to represent dates in JSON). Btw, Rick Strahl has a several good post on JQuery. Here’s a good one that presents all the methods you can use for AJAX calls (and some of their caveats). In order to get the correct date in the client, we’re really forced to use the JavaScriptSerializer class. In fact, if you run the previous sample, you’ll see that time is really a string with the custom format used by the MS server platform for dates.

Before ending, there’s still time to mention the Json method that your controller inherits from the Controller class. There are several overloads of this method which let you specify all the available the properties of the JsonResult class.