Click here to Skip to main content
13,199,669 members (38,632 online)
Click here to Skip to main content
Add your own
alternative version

Stats

31.1K views
10 bookmarked
Posted 21 Jul 2011

Using jQuery to Consume ASP.NET MVC JSON Services

, 21 Jul 2011
Rate this:
Please Sign up or sign in to vote.
How to use jQuery to consume ASP.NET MVC JSON services

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 a 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);
  }
  ...
}
</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:

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 applications 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 scenes 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 it 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 Service 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)

Share

About the Author

Alexander Turlov
Architect
Canada Canada
Alexander Turlov is a professional software development consultant that has been working in IT industry since 1987. His programming experience includes such languages as FORTRAN, Pascal, Basic, C, C++ and C#. He's been working for different industries including but not limited to science, manufacturing, retail, utilities, finance, insurance, health care, education and so on. His area of professional interests is cloud powered 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, Azure and Visual Studio Team Services as his primary tools. He holds a M.Sc. degree in physics and various industry certifications including MCSD.NET, Azure and Scrum.

View my profile on LinkedIn

View my blog

You may also be interested in...

Pro
Pro

Comments and Discussions

 
GeneralMy vote of 2 Pin
afzal.gujrat26-Feb-13 8:33
memberafzal.gujrat26-Feb-13 8:33 
GeneralMy vote of 2 Pin
samthec27-Sep-12 4:08
membersamthec27-Sep-12 4:08 
GeneralRe: My vote of 2 Pin
Alexander Turlov4-Oct-12 4:50
memberAlexander Turlov4-Oct-12 4:50 
Sorry about your confusion but don't blame the article: the confusion is in your head. The approach described in the article IS A WEB SERVICE since it serves a non-HTML content via HTTP protocol. You may be confusing with ASMX WEB SERVICE which used to be a standard de-facto in ASP.NET until v3.5. If it is the case you need to learn a difference between ASMX WEB SERVICE and a GENERIC WEB SERVICE. Both are WEB services because they communicate via HTTP. But implementation is different hence the ASMX vs. GENERIC.
Alexander Turlov
Experienced software developer/architect
MCSD.NET

Questionhaving problem ....... Pin
manoj kumar choubey9-Aug-12 20:55
membermanoj kumar choubey9-Aug-12 20:55 
AnswerRe: having problem ....... Pin
Alexander Turlov21-Sep-12 4:37
memberAlexander Turlov21-Sep-12 4:37 
GeneralRe: having problem ....... Pin
manoj kumar choubey22-Sep-12 5:15
membermanoj kumar choubey22-Sep-12 5:15 

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

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

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