Sponsored

Tuesday, July 12, 2011

Using jQuery to Consume ASP.NET MVC JSON Services

Since the inception of ASP.NET Web Services have been an important part of any professional web developer's tool set. Starting .NET 3.5 Web Services became even more useful as it became possible to call Web Services asynchronously from a browser using JavaScript and ASP.NET AJAX.

However for the last two years the alternative ASP.NET MVC framework has been drawing more and more attention from the development community due to its good implementation of the MVC design pattern and adherence to web standards and bleeding edge web technologies.

For many experienced ASP.NET developers accustomed to Web Services especially accompanied with ASP.NET AJAX framework a natural question occurs: how to implement similar approach with ASP.NET MVC framework and its natural JavaScript companion jQuery?

ASP.NET MVC JSON Services

First of all there is no concept of Web Services in ASP.NET MVC however it is very easy to implement its functional analog. Any Controller Action method that returns data rather than an HTML formatted page can be considered an analog of a Web Method and used correspondingly. From this point of view a set of Controller Action methods that return properly formatted JSON response I will call MVC JSON Services. Below is a simple example:


public class JsonServicesController : Controller
{
  ...
  public JsonResult MyJsonMethod()
  {
      // ... acquire an instance of an object
      return Json(data);
  }
  ...
}

The code above when properly implemented should return a JSON representation of the data object and that is an illustration of how easy it is to implement an MVC JSON Service method.

Security

By default a JSON Service method will throw an exception when called by an HTTP GET request. This behavior is in accordance with the behavior of a regular ASP.NET Web Service method that also would not accept a GET request. This is also considered a best practice to call a JSON Service method only by HTTP POST request. In order to implement that an [HttpPost] attribute should be applied to a JSON Service method. If you would like to learn more about security considerations read this post.

Another consideration is authentication/authorization. Similarly to any other Controller Action method an [Authorize] attribute applied to the JSON Service method controls that the method can only be called by an authenticated user with proper authorization (if required).

Now the corrected JSON Service method will look like this:

public class JsonServicesController : Controller
{
  ...
  // uncomment below if authentication required
  //[Authorize]
  [HttpPost]
  public JsonResult MyJsonMethod()
  {
      // ... acquire an instance of an object
      return Json(data);
  }
  ...
}

How to use jQuery to call an MVC JSON Service method

One of the most popular application for JSON Services is to call them from JavaScript asynchronously and then use returned data to update the HTML content. With regular ASP.NET and ASP.NET AJAX such an exercise would be easy to accomplish as all the necessary JavaScript code is automatically generated and referenced on the page. That convenience however comes with a price of bigger payload and longer loading time as many additional scripts must be referenced on a page.

In ASP.NET MVC natural JavaScript environment is jQuery library that has everything we need in order to accomplish our task. See the code example below:

  function getMyObject(onSuccess) {
    $.ajax({
       type: "POST",
       contentType: "application/json;charset=utf-8",
       url: "/JsonService/MyJsonMethod",
       data: "{}",
       dataType: "json",
       success: onSuccess
    });
  }

We use a jQuery.ajax method to make an asynchronous POST request to our JSON Service method. Notice contentType and dataType properties that are responsible for identifying that we are requesting and expecting back JSON-formatted data. The url property defines the URL of our JSON Service method constructed based on standard ASP.NET MVC Routing rules. The value of the success parameter is a callback function name that will be called when the request completes successfully.

Input parameters

Rarely the Service methods are called without parameters. In case of one or two simple parameters we can rely on ASP.NET MVC Routing automatic parameters mapping feature that will automatically extract a parameter from the URL and then pass it to a Service method. Look at the example.

Let's assume we would like to call a JSON Service method with a single parameter "id" that is used to acquire our data object on the server side. First we'll have a corresponding routing rule defined in the global.asax.cs file:

  public static void RegisterRoutes(RouteCollection routes)
  {
     ...
     routes.MapRoute(
          "JsonService",
          "{controller}/{action}/{id}",
          new { controller = "JsonServices", action = "GetData", id = UrlParameter.Optional } 
     );
     ...
  }

Next we'll have a JSON Service method with a parameter:

public class JsonServicesController : Controller
{
  ...
  // uncomment below if authentication required
  //[Authorize]
  [HttpPost]
  public JsonResult MyJsonMethod(string id)
  {
      // ... acquire an instance of an object
      return Json(data);
  }
  ...
}

When we call our JSON Service method using a URL like "JsonServices/MyJsonMethod/123456" the method will receive a string value "123456" as an id parameter automatically.

That was simple. Now what if we need to pass a complex object as a parameter and we cannot use URL? In this case we just pass a JSON literal as a string representing our complex parameter using a data property in the jQuery.ajax method:

  function getMyObject(onSuccess) {
    $.ajax({
       type: "POST",
       contentType: "application/json;charset=utf-8",
       url: "/JsonService/MyJsonMethod",
       data: '{"id":"123456", "title":"object title"}',
       dataType: "json",
       success: onSuccess
    });
  }

Now we need to modify our JSON Service method in order to receive the parameter correctly.

public class JsonServicesController : Controller
{
  ...
  // uncomment below if authentication required
  //[Authorize]
  [HttpPost]
  public JsonResult MyJsonMethod(MyObject param)
  {
      // ... acquire an instance of an object
      return Json(data);
  }
  ...
}

We need to define a MyObject class as the following:

  [Serializable]
  public class MyObject {
      public string Id { get; set; }
      public string Title { get; set; }
  }

Notice that the class is marked with a [Serializable] attribute and names of the public properties match exactly the ones we used in a JSON parameter string in the jQuery.ajax function call. This is just enough for the ASP.NET MVC framework to do all the work behind the scene and provide our JSON Service method with the correct parameter value. It's easy to see a similarity between this asynchronous AJAX call and a regular form POST request with the only difference that a parameter on the client side is provided as a JSON literal string.

Consuming returned data

Our final goal is to receive a JSON-formatted piece of data that we'll be able to consume by JavaScript and we hope to minimize our efforts by fully exploiting abilities of the ASP.NET MVC framework and jQuery library. So far we've managed to make a request to a server-side JSON Service method and the next step is to consume the returned data. We have provided the onSuccess JavaScript function as a callback to the jQuery.ajax method and we should use it for all the data processing we want.

  function onSuccess(data) {
    //example of a simple data processing
    var message = data.ResultMessage;
    $("#resultMessage").html(message);
  }

When the AJAX request completes the onSuccess function is called and receives a parameter data that is our expected result. data is already a regular JavaScript object that has been deserialized from a JSON string and we can use as intended. It fully corresponds to a server-side data object that we have returned from a JSON Service method. Notice that as opposed to a regular Web Service call with ASP.NET AJAX the returned object is not wrapped in a "d" property so there is no need for additional processing.

A word about DateTime

If a returned object contains a property of a DateTime type the MVC framework returns it in a specific form that requires some preliminary processing on the client side before can be consumed. A simple function below converts a value returned by the MVC framework into a standard JavaScript Date object:

  function toDate(dateValue) {
      return eval('new' + dateValue.replace(/\//g, ' '));
  }

Please read this post and do some Internet search to better understand the mechanics of DateTime value format transformation when returned in a JSON-formatted message.

Conclusion

In this article we have learned how to implement a JSON Services using ASP.NET MVC framework and how to call JSON Services methods asynchronously from JavaScript using jQuery library.

4 comments:

  1. Hello Sir,

    I followed your tutorial to the letter,however when the call gets to "public JsonResult MyJsonMethod(MyObject param)" the param values are null. It looks like an empty new instance of the object

    ReplyDelete
    Replies
    1. 1. check that parameter name in the JavaScript is exactly the same as in the C# code; 2. make sure all the members in the C# class that represents a parameter are properties, not fields.

      Delete