Handling JSON Arrays returned from ASP.NET Web Services with jQuery

4.57 (147 votes)

There appear to be many articles showing how to use jQuery with ASP.NET Web Services around, but the vast majority of them illustrate the use of PageMethods that return a single value - typically "Hello World!" or the current date and time. Not much use in the real world, where you may more often need to call a service that returns a collection of complex objects. Here are a couple of examples that look at playing with more than just simple values.

The Web Service methods that I will use revolve around cars. Having set up a web site in Visual Studio 2008, I have added a new item of type "Web Service" to the project, calling it CarService.asmx. The code-behind - CarService.cs - is automatically generated within the App_Code folder. The full code for that class file is as follows:


using System;

using System.Web;

using System.Web.Services;

using System.Web.Services.Protocols;

using System.Web.Script.Services;

using System.Collections.Generic;

using System.Linq;


public class Car


    public string Make;

    public string Model;

    public int Year;

    public int Doors;

    public string Colour;

    public float Price;



/// <summary>

/// Summary description for CarService

/// </summary>


[WebService(Namespace = "http://tempuri.org/")]

[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]



public class CarService : WebService



    List<Car> Cars = new List<Car>{

    new Car{Make="Audi",Model="A4",Year=1995,Doors=5,Colour="Red",Price=2995f},

    new Car{Make="Ford",Model="Focus",Year=2002,Doors=5,Colour="Black",Price=3250f},

    new Car{Make="BMW",Model="5 Series",Year=2006,Doors=4,Colour="Grey",Price=24950f},

    new Car{Make="Renault",Model="Laguna",Year=2000,Doors=5,Colour="Red",Price=3995f},

    new Car{Make="Toyota",Model="Previa",Year=1998,Doors=5,Colour="Green",Price=2695f},

    new Car{Make="Mini",Model="Cooper",Year=2005,Doors=2,Colour="Grey",Price=9850f},

    new Car{Make="Mazda",Model="MX 5",Year=2003,Doors=2,Colour="Silver",Price=6995f},

    new Car{Make="Ford",Model="Fiesta",Year=2004,Doors=3,Colour="Red",Price=3759f},

    new Car{Make="Honda",Model="Accord",Year=1997,Doors=4,Colour="Silver",Price=1995f}




    public List<Car> GetAllCars()


        return Cars;





    public List<Car> GetCarsByDoors(int doors)


        var query = from c in Cars

                    where c.Doors == doors

                    select c;

        return query.ToList();




A Car class is created at the top of the code, which has a number of properties of different types: strings, ints and floats. The Web Service itself is decorated with the [ScriptService] attribute, which denotes that the service can be called from Javascript. It also ensures that the data returned is a JSON string representing a single object or an array of objects, depending on the functionality of the service.

A List<Car> is instantiated, and populated with a number of Car objects. The syntax makes use of the object and collection intitialisers that were introduced in C# 3.0. Two simple methods are each decorated with the [WebMethod] attribute. The first one simply returns the List<Car> Cars that was created, whereas the second one makes use of LINQ to return only those Cars that have the number of doors that the method accepts as a parameter. There's nothing particularly fancy or clever in any of this, except to repeat the point that the [ScriptService] attribute is vital to making the methods usable by AJAX.

The mark-up in the aspx page that will call the Web Service is extremely simple:


<form id="form1" runat="server">

<input type="button" id="Button1" value="Get Cars" />

<div id="output"></div>



All that's needed now is some Javascript for the getCars() method that has been assigned to the onclick event of the html button. This will go into the <head> section of the page:


<script type="text/javascript" src="script/jquery-1.2.6.min.js"></script>

<script type="text/javascript">


  $(function() {




  function getCars() {


      type: "POST",

      url: "CarService.asmx/GetAllCars",

      data: "{}",

      contentType: "application/json; charset=utf-8",

      dataType: "json",

      success: function(response) {

        var cars = response.d;


        $.each(cars, function(index, car) {

          $('#output').append('<p><strong>' + car.Make + ' ' +

                                car.Model + '</strong><br /> Year: ' +

                                car.Year + '<br />Doors: ' +

                                car.Doors + '<br />Colour: ' +

                                car.Colour + '<br />Price: £' +

                                car.Price + '</p>');



      failure: function(msg) {







First, jQuery is referenced via the src attribute of the first <script> tag. Then a click event is registered with the button which will invoke the getCars() function. After that is the getCars() function that is fired when the button is clicked. It makes use of the $.ajax(options) function within jQuery, and accepts an object with a number of optional properties. type specifies the HTTP method, which in this case is POST. url specifies the URL of the Web Service, together with the web method that is being called. This is followed by the parameters, which are applied to the data property. In this case, no parameters are being passed, as we are calling the method that retrieves the entire collection of Cars. The contentType and dataType MUST be specified. Following this are two further functions: success defines what should be done if the call is successful, and failure handles exceptions that are returned.

In this case, the success callback is passed the resulting HTTP response. response in this case looks like this in FireBug:

You can see that an object with a property - d - is returned, which contains an array of objects. Each object has a __type property which tells you that it is a Car object, followed by the other properties of our Web Service Car object. The div with the id of output is emptied, in case there was clutter there from a previous ajax call. The jQuery each() function is used to iterate over the collection of objects. Each car object is accessed in turn, and its properties are written to a paragraph, which is then appended to the content of div output. the result looks like this:

We'll add a DropDownList to the aspx file, so that we can make use of the second Web Method, which retrieves cars that meet the Number of Doors criteria:


<form id="form1" runat="server">


  Number of doors:

  <asp:DropDownList ID="ddlDoors" runat="server">







<input type="button" id="Button1" value="Get Cars" onclick="getCars();" />

<div id="output"></div>



Only two lines in the previous Javascript need to be changed and these are shown in bold:


<script type="text/javascript" src="script/jquery-1.2.6.min.js"></script>

<script type="text/javascript">


  function getCars() {


      type: "POST",

      url: "CarService.asmx/GetCarsByDoors",

      data: "{doors: " + $('#<%= ddlDoors.ClientID %>').val() + " }",

      contentType: "application/json; charset=utf-8",

      dataType: "json",

      success: function(response) {

        var cars = response.d;


        $.each(cars, function(index, car) {

          $('#output').append('<p><strong>' + car.Make + ' ' +

                                car.Model + '</strong><br /> Year: ' +

                                car.Year + '<br />Doors: ' +

                                car.Doors + '<br />Colour: ' +

                                car.Colour + '<br />Price: £' +

                                car.Price + '</p>');



      failure: function(msg) {







The url option now points to the appropriate method, and a parameter is passed into the data option, which uses jQuery syntax to reference the selected value from the DropDownList. I have used inline ASP.NET tags in this case to dynamically render the ID of the DropDownList using the ClientID property, so that there will be no issues in referencing the DropDownList if this code was transferred to a User Control or another control that implements INamingContainer. Now when the page is run, and an option selected, the button click event results in just those cars matching the number of doors in the DropDownList being returned:

Date Posted:
Last Updated:
Posted by:
Total Views to date: 339712


- Shail

Nice Article!
Just one question if I need to use JSON and jQuery in ASP.Net 2.0 what all I need to do. We are still using ASP.Net 2.0

- Mike


In 2.0, there is no "d" object in the response, so you would access the properties of the object directly from"response".

A clearer explanation is proviced here:


- viet

That's great! Thank you.

- Dan Sylvester

Really cool Mike. Those are great webmethod examples written in linq!

- Nasir

Great mike Thank you very much

- Gufran Sheikh


Nice Article, but isn't it be good to have the returned data directly in the Object Datasource or in Dataset that is connected to the GridView, Details View, Repeater or any Data Controls ?

Because here you are generating the html in the code which is good for small forms but for large forms I dont think so it will be good idea.

Please advice.

Gufran Sheikh

- Mike


No. The whole point of the article is to illustrate how to manage this using client-side technology. Using server-side technology requires postbacks. It also forces all the processing and html generation to be done on the web server for all visitors. The approach illustrated above distributes the html generation to individual user's PCs.

If you used ASP.NET AJAX, you could bind data using a DataSource control, but then you would be returning all the html as well as the data - as well as posting a whole mess of stuff between calls such as ViewState etc. I've seen many posts in forums complaining of poor performance when people have shoved a GridView in an UpdatePanel and then bound it before the html is returned back to the browser. jQuery solves that problem.

In my view, ASP.NET AJAX is quite horrible. However, in the next version of ASP.NET (4.0) Microsoft will be introducing client-side templates where you can bind the data to a table or similar and generate the html on the client. There are a number of jQuery plugins already that allow you to do the same thing.

- Paul Speranza


I am new to JQuery and so far I have been doing my callbacks exactly the way that you are showing.

My question is, the webmethod attribut seems to work fine but I have just found out about JSON.Net. Why would we even need that?

- Mike


Why should we bother about what? JSON.NET? Or the WebMethod attribute? It's actually the [ScriptService] attribute that enables the web service to return JSON formatted data (instead of SOAP messages) through a proxy that is automatically generated on behalf of the service.

- wiglebot

This example helps me out on many issues I have been working through the last few days. Thanks.

- Sangam Uprety

Nice article.
I have coded to fetch data in json format, but it is throwing error. However, I have been successful at retrieving the required data in the xml format. The response as tracked by firebug is:

Post: {property: 200 }
Response: System.InvalidOperationException: Request format is invalid: application/json; charset=utf-8. at System.Web.Services.Protocols.HttpServerProtocol.ReadParameters() at System.Web.Services.Protocols.WebServiceHandler.CoreProcessRequest()

Here is my ajax call:

function getData() {
type: "POST",
url: "WebService.asmx/FetchDataByType",
data: {'property':200},
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(response) {
var vars = (typeof response.d) == 'string' ? eval('(' + response.d + ')') : response.d;
for (var i = 0; i < vars.length; i++) {

failure: function(msg) {

What could be the reason? Thank you.

- RGuillen

@Sangam Uprety

You should try to add httpHandlers section to Web.config file like this:

<remove verb="*" path="*.asmx"/> <add verb="*" path="*.asmx" type="System.Web.Script.Services.ScriptHandlerFactory" validate="false"/>

Hope it helps.

- Mayur Unagar

Thanks a lot! Very nice article. My whole day headache overcome after reading this article.

- Adil Saud

Very good article,

I like the way information has been fetched from web service, specially without taking the static web reference OR instantiating web service's method dynamically at code behind end.


- rakibul Islam

Very nice article that i was looking for. many thanks

- Nathan Prather

Great Article, Thanks!

- Vlad

Thanks Man.

- Richard

great article!!!

- Edmilson

Hi, I lost almost one day looking for this answer,



- karl

wiked woking example, woop. im rocking now.......

thanks very much very good example......

- David

Thanks for posting this helpful article.

To make it even more "real-world", would you mind explaining the diifferences required if the data was obtained from a database, ie how would you send a DataTable in json format?

- Mike


If you serialize a DataTable, you get XML. But I should maybe update this article to discuss serialising data to JSON using the JavaScriptSerializer class for serializing POCO classes.

- Atul Kumar Singhal

How to reverse of it.

That means : How to send array object from javascript using ajax and how to get by C# of this object.

Please send me any link to reverse query.

- Ghulam Haider

Excellent article with simple and to the point description.....!

- Juber N. Mulani

working since last 3 days on this
u solved my problem
thanks a ton !!!!

- Madhusudan

Thanks.... This article is really very helpful to all... This gives the the clear and exact knowledge what i was looking for. thanks once again...

- Asif Iqbal

Awesome technique. I had been finding since long..

Thank you.

- Altaf Patel

nice example. clean and brief.

- Leonitus

Wow, I did not know you can use Json like this. Enlightening, thank you!

- Nacho

Thank you, works great and very well explained.

- William

Thanks for writing this great article! This really helped me finish the project I'm working on.

Great blog Mike!

- skyfly

When You people will make little more effort and use pure js?

- Mike


What for? Why would anyone want to waste time writing loads of js when they can use jQuery to simplify this kind of thing?

Recent Comments

Jon 31/03/2016 21:36
In response to Exploring Prefix: A Free ASP.NET Profiling Tool
We had the exact same experience, finding multiple bugs in an application that we thought was pretty...

ranjith 31/03/2016 05:50
In response to A Better Way To Export Gridviews To Excel
Hello Mike. i am exporting from gridview, because i have some images in my gridview. but i am error...

Matt Watson 30/03/2016 22:19
In response to Exploring Prefix: A Free ASP.NET Profiling Tool
Glad you are loving it! Matt from Stackify...

Dmitry 28/03/2016 04:26
In response to Solved - The Microsoft.ACE.OLEDB.12.0 provider is not registered on the local machine
thank you about the VS 32-bit remark...

federico 26/03/2016 11:29
In response to Request.Form Is Empty When Posting To ASPX Page

Micheal 23/03/2016 00:58
In response to ASP.NET MVC 5 with EF 6 - Working With Files
Thanks for the code. its pretty straightforward. worked for me on my first trial. Perfect!...

Francisco 22/03/2016 20:35
In response to ASP.NET MVC 5 with EF 6 - Working With Files
The post is very good, thanks...

Nick Brown 22/03/2016 13:53
In response to Adding A View
Hi, Many thanks for this tutorial, it's helping me get started with MVC. In VB (VS 2013) I get late...

ferry mae 22/03/2016 13:04
In response to Send form content by email in ASP.NET
do i need to change this? message.To.Add(new MailAddress("me@domain.com")); message.CC.Add(new you...

Keith 22/03/2016 12:02
In response to Creating a Connection String and Working with SQL Server LocalDB
As always worst explanation, but this time you rocked with plagiarism too .. huhh.. copied from Rick...