Click here to Skip to main content
Click here to Skip to main content

Using jQuery to Consume ASP.NET MVC JSON Services

, 21 Jul 2011
Rate this:
Please Sign up or sign in to vote.
IntroductionSince 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

Introduction

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:
<script class="brush: csharp" type="syntaxhighlighter">
public class JsonServicesController : Controller
{
  ...
  public JsonResult MyJsonMethod()
  {
      // ... acquire an instance of an object
      return Json(data);
  }
  ...
}
</script>

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:

<script class="brush: csharp" type="syntaxhighlighter">
public class JsonServicesController : Controller
{
  ...
  // uncomment below if authentication required
  //[Authorize]
  [HttpPost]
  public JsonResult MyJsonMethod()
  {
      // ... acquire an instance of an object
      return Json(data);
  }
  ...
}
</script>

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:

<script class="brush: javascript" type="syntaxhighlighter">
  function getMyObject(onSuccess) {
    $.ajax({
       type: "POST",
       contentType: "application/json;charset=utf-8",
       url: "/JsonService/MyJsonMethod",
       data: "{}",
       dataType: "json",
       success: onSuccess
    });
  }
</script>
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:

<script class="brush: csharp" type="syntaxhighlighter">
  public static void RegisterRoutes(RouteCollection routes)
  {
     ...
     routes.MapRoute(
          "JsonService",
          "{controller}/{action}/{id}",
          new { controller = "JsonServices", action = "GetData", 
              id = UrlParameter.Optional } 
     );
     ...
  }
</script>
Next we'll have a JSON Service method with a parameter:
<script class="brush: csharp" type="syntaxhighlighter">
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);
  }
  ...
}
</script>
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:

<script class="brush: javascript" type="syntaxhighlighter">
  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
    });
  }
</script>
Now we need to modify our JSON Service method in order to receive the parameter correctly.
<script class="brush: csharp" type="syntaxhighlighter">
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);
  }
  ...
}
</script>
We need to define a MyObject class as the following:
<script class="brush: csharp" type="syntaxhighlighter">
  [Serializable]
  public class MyObject {
      public string Id { get; set; }
      public string Title { get; set; }
  }
</script>
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.
<script class="brush: javascript" type="syntaxhighlighter">
  function onSuccess(data) {
    //example of a simple data processing
    var message = data.ResultMessage;
    $("#resultMessage").html(message);
  }
</script>
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:
<script class="brush: javascript" type="syntaxhighlighter">
  function toDate(dateValue) {
      return eval('new' + dateValue.replace(/\//g, ' '));
  }
</script>
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.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

About the Author

Alexander Turlov
Architect
Canada Canada
Alexander Turlov has been working in IT industry since 1987. His programming experience includes such languages as FORTRAN, Pascal, and Basic, C, C++ and C#. He's been working for different industries like science, manufacturing, retail, utilities, finance, insurance, health care, education and so on. His area of interests is rich web applications development with .NET, C#, ASP.NET/MVC and JavaScript. He is working in software development doing architecture, design and development on .NET platform and using Microsoft Visual Studio, IIS and SQL Server as his primary tools, and a lot of other commercial and open source frameworks and tools. He holds a M.Sc. degree in physics and an MCSD.NET certification.

View my profile on LinkedIn

View my blog
Follow on   Twitter

Comments and Discussions

 
Questionhaving problem ....... Pinmembermanoj kumar choubey9-Aug-12 20:55 
AnswerRe: having problem ....... PinmemberAlexander Turlov21-Sep-12 4:37 
GeneralRe: having problem ....... Pinmembermanoj kumar choubey22-Sep-12 5:15 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Mobile
Web01 | 2.8.140721.1 | Last Updated 21 Jul 2011
Article Copyright 2011 by Alexander Turlov
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid