Click here to Skip to main content
15,867,594 members
Articles / Web Development / ASP.NET

Create a JSON WebService in ASP.NET 2.0 with a jQuery Client

Rate me:
Please Sign up or sign in to vote.
4.88/5 (35 votes)
27 Nov 2009CPOL6 min read 341.4K   13.4K   116   28
Create an ASP.NET Web Service which returns data in JSON format and call it from a jQuery client.

Introduction

We know that, by default, an ASP.NET Web Service returns data in XML format. Processing XML data over wire always involves some overhead. These days, another format called JSON is very popular in overcoming some of these issues. In .NET 3.5 onwards, Microsoft provides this functionality inbuilt in ASP.NET 3.5, but a lot of applications are still running on ASP.NET 2.0. In this article, I will show how easily you can return JSON format data from a Web Service and consume it from jQuery, a very popular, lightweight JavaScript library.

Background

Sometime back, I was working on a project which involved a lot of Web Service calls. Processing XML data was taking more time than I had planned, and I decided to return data in JSON format, which is very lightweight and is easily processed at the client end by JavaScript. For example, we have an "Employee" class that contains five fields: "Name", "Company", "Address", "Phone", and "Country". When you return the data from the Web Service in the default format (XML), you will get something like this:

JSONDemo

When you return data in JSON format, you will get something like this:

JSONDemo

If you compare both the values, you will find that JSON returns only a string value without the overhead of XML node processing. All you need to do is process the string, which is in the form of Name:Value pairs. Before I move ahead, I want to give some heads-up for JSON (JavaScript Object Notation). It is a lightweight data-interchange format. It is a text format that makes it completely language independent. JSON is built on two data structures:

  • A collection of name/value pairs. This is normally called a Dictionary, Hashtable etc.
  • An ordered list of values. This is normally called an array, list, sequence etc.

You can read more about JSON from json.org.

Requirements

You can also use Microsoft Web Platform Installer 2.0 to install all the required software from a single place to develop web based application. This also includes IIS.

Now, let’s discuss how we implement the solution.

Install ASP.NET AJAX Extensions 1.0. The default directory of installation is “Program Files\Microsoft ASP.NET\ASP.NET 2.0 AJAX Extensions\v1.0.61025”. The directory structure looks like this:

JSONDemo

System.Web.Extension.dll is the main DLL that performs all the magic. You can also install the Visual Studio 2008 Template for AJAX Extension.

Implementation

Create a sample ASP.NET Web Service page and name it JSONDemo.

JSONDemo

After the Web Service application is created, rename it to JSON and add a reference to System.Web.Extensions.dll. After adding the reference, the application looks like this:

JSONDemo

Configure Web.Config

To make things working, we need to add a section for the ScriptHandlerFactory HttpHandler using the following code snippet under the <system.web> section:

XML
<httphandlers>
 <remove verb="*" path="*.asmx"></remove>
  <add verb="*" path="*.asmx" 
     type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions,
     Version=1.0.61025.0, Culture=neutral,PublicKeyToken=31bf3856ad364e35">
 </add>
</httphandlers>

Add Class

Now we add one class name Employee to use in web service.

C#
public class Employee
{
    public string Name { get; set; }
    public string Company { get; set; }
    public string Address { get; set; }
    public string Phone { get; set; }
    public string Country { get; set; }
}

Configure the ASMX Web Service

If you open system.web.extension.dll in an object browser, you will find these namespaces:

JSONDemo

JSONDemo

Now, we add the System.Web.Script.Services and System.Web.Script.Serialization namespaces. The using statement list looks like this:

C#
using System;
using System.Collections.Generic;
using System.Web;
using System.Web.Services;
using System.Web.Script.Services;
using System.Web.Script.Serialization;

Now we can add the ScriptService a part of the System.Web.Script.Services namespace attribute in the class. Applying this attribute makes the Web Service call easy from JavaScript. This attribute also causes the Web Service to accept JSON (JavaScript Object Notation) data for the input parameters and to return JSON data. This also completely eliminates the need to parse the XML.

After adding the ScriptService attribute, add ScriptMethod(ResponseFormat = ResponseFormat.Json) to return data in JSON format.

The Web Service decorated with ScriptService attribute, by default, returns data in JSON format as opposed to in XML format. So you don’t even need to add the ResponseFormat.Json attribute. But if you want that in your Web Service, have some web method also return data in XML format, then specifically tell the web method by adding: ScriptMethod(ResponseFormat = ResponseFormat.Xml). In my example, I added this attribute just for clarity.

After applying all the above, this is how your code looks like:

C#
namespace JSONDemo
{
    /// <summary>
    /// Summary description for Service1
    /// </summary>
    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [System.ComponentModel.ToolboxItem(false)]
    [ScriptService]
    public class JSONService : System.Web.Services.WebService
    {

        [WebMethod]
        [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
        public string TestJSON()
        {
            Employee[] e = new Employee[2];
            e[0] = new Employee();
            e[0].Name = "Ajay Singh";
            e[0].Company = "Birlasoft Ltd.";
            e[0].Address = "LosAngeles California";
            e[0].Phone = "1204675";
            e[0].Country = "US";
            e[1] = new Employee();
            e[1].Name = "Ajay Singh";
            e[1].Company = "Birlasoft Ltd.";
            e[1].Address = "D-195 Sector Noida";
            e[1].Phone = "1204675";
            e[1].Country = "India";
            return new JavaScriptSerializer().Serialize(e);
        }
        [WebMethod]
        [ScriptMethod(ResponseFormat = ResponseFormat.Xml)]
        public Employee[] TestXML()
        {
            Employee[] e = new Employee[2];
            e[0] = new Employee();
            e[0].Name = "Ajay Singh";
            e[0].Company = "Birlasoft Ltd.";
            e[0].Address = "LosAngeles California";
            e[0].Phone = "310-235-1535";
            e[0].Country = "US";
            e[1] = new Employee();
            e[1].Name = "Ajay Singh";
            e[1].Company = "Birlasoft Ltd.";
            e[1].Address = "D-195 Sector Noida";
            e[1].Phone = "120-467500";
            e[1].Country = "India";
            return e;
        }
    }
}

Now we are ready with our Web Service. You can test this Web Service directly from the browser. I will show you how to call this Web Service from a normal HTML page using jQuery. But if you don’t want to use jQuery and want to use the Microsoft ASP.NET AJAX Script Manager to call the Web Service from client-side, a JavaScript proxy class is generated. You can see the JavaScript proxy class by using the "/js" parameter after the .asmx page.

For example, http://localhost/jsondemo/JSON.asmx/js.

Calling a Web Service Using jQuery

Below is the code to call a Web Service from jQuery:

JavaScript
function testJson() {
    $.ajax({
        type: "POST",
        url: "JSON.asmx/TestJSON",
        data: "{}",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function(msg) {
            var data = eval("(" + msg + ")");
            var t = "<table border=1> <tr>" +
              "<td> <strong>Name</strong></td> <td> " +
              "<strong>Company</strong></td> <td> " +
              "<strong>Address</strong></td> <td> " +
              "<strong>Phone</strong></td> <td> " +
              "<strong>Country</strong></td> </tr> ";
            jQuery.each(data, function(rec) {
                t = t + " <tr> <td> " + this.Name + "</td> <td> " +
                    this.Company + "</td> <td> " + this.Address +
                     "</td> <td> " + this.Phone + 
                     "</td> <td> " + this.Country + 
                     "</td> </tr> ";
            });

            t = t + " </table> ";

            $("#jsonDiv").html(t);
        },
        error: function(msg) {

        }
    });
};

$.ajax() is a jQuery method to make AJAX calls. It takes various parameters. The description of the various parameters are:

  • type: you always make a “POST” request while calling a Web Service.
  • url: the Web Service URL along with the web method name.
  • In the above example, “JSON.asmx” is the web service URL and TestJSON is a web method.

  • data: used to pass a parameter to a web method.
  • contentType: when calling a JSON Web Service, you always need to set this as "application/json; charset=utf-8".
  • dataType: based on the kind of Web Service call, you need to set the value; for a JSON call, it should be "json".
  • success: here, define a function which is called after successful processing; in the above example, I define an anonymous function for processing the data returned by the Web Service call. You can also define it as:

    JavaScript
    function (msg) { var data = eval("(" + msg + ")"); 
        ProcessWebServiceResult(data) //javascript function }

    In ASP.NET 2.0, a Web Service call is processed different as compared to ASP.NET 3.5. That is the reason we use the eval function. If you are using ASP.NET 3.5, you can simply use msg.d, where d is the property of the message response that contains the content. One more thing I would like to explain in the function (msg) statement is, the msg parameter name could be any name you want. What jQuery does is, it assigns the message response in this parameter and then you can process it accordingly.

  • error: Here, you can use an anonymous function or a separate function to handle errors, if any returned.

Here is the output when you click the JSON button:

JSONDemo

Summary

From all the above, you can see how easy it is to implement a JSON Web Service in ASP.NET 2.0 and call it from a normal HTML page using jQuery. The reason for writing this article is, when I started working on this, I faced a lot more problems because I didn’t find all the information in a single place. I have attached a complete working example that I illustrated above. In this project, I have also included “System.Web.Extensions.dll” so you don’t even need to download the ASP.NET AJAX 1.0 Extensions if you want to create a JSON Web Service. But if you want to use ASP.NET AJAX in place of jQuery for client-side processing, then you need to download it. I hope this article helps you to understand some of the concepts, all in a single place. Any feedback is really appreciated.

License

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


Written By
Technical Lead Birlasoft Ltd.
India India
I am working with Birlasoft as a tech lead from 3 years.

Comments and Discussions

 
QuestionJson data not working Pin
Ajaaz219-Dec-14 22:24
Ajaaz219-Dec-14 22:24 
QuestionmaxJsonLength in 2.0 ?? Pin
prateek bhardwaj6028-Aug-14 1:56
prateek bhardwaj6028-Aug-14 1:56 
Question500 Error When i write <httphandlers> Pin
gkaradagan12-Mar-13 8:42
gkaradagan12-Mar-13 8:42 
AnswerRe: 500 Error When i write <httphandlers> Pin
HSUPOWEI27-Mar-13 16:08
HSUPOWEI27-Mar-13 16:08 
QuestionCross-Domain? Pin
andrewhelgeland18-Jul-12 8:01
andrewhelgeland18-Jul-12 8:01 
QuestionRe: Cross-Domain? Pin
olivercortinas29-Dec-14 2:52
olivercortinas29-Dec-14 2:52 
GeneralMy vote of 5 Pin
Member 1051082217-Jun-12 1:20
professionalMember 1051082217-Jun-12 1:20 
QuestionError Pin
natarajangovindavel10-Apr-12 22:08
natarajangovindavel10-Apr-12 22:08 
AnswerRe: Error Pin
Jaison Devasia25-Mar-14 12:48
Jaison Devasia25-Mar-14 12:48 
QuestionI´ve got an Error Pin
yellow_lucky26-Jan-12 2:41
yellow_lucky26-Jan-12 2:41 
Questiongreat example, but still xml format Pin
xin gong27-Dec-11 10:02
xin gong27-Dec-11 10:02 
AnswerRe: great example, but still xml format Pin
xin gong27-Dec-11 10:07
xin gong27-Dec-11 10:07 
AnswerRe: great example, but still xml format Pin
natarajangovindavel10-Apr-12 22:02
natarajangovindavel10-Apr-12 22:02 
GeneralMy vote of 1 Pin
Member 79268046-Oct-11 22:04
Member 79268046-Oct-11 22:04 
Questionwhere is the code behind file? Pin
jeyanth22-Aug-11 7:46
jeyanth22-Aug-11 7:46 
GeneralMy vote of 1 Pin
Ashish Sharma11-Feb-11 18:47
Ashish Sharma11-Feb-11 18:47 
GeneralSome changes to make it work. Pin
thomasa26-Nov-10 5:23
thomasa26-Nov-10 5:23 
GeneralRe: Some changes to make it work. Pin
davida377-Feb-15 21:26
davida377-Feb-15 21:26 
GeneralGreat example but what about cross domain Pin
Super Boss30-Apr-10 13:23
Super Boss30-Apr-10 13:23 
GeneralRe: Great example but what about cross domain Pin
andrewhelgeland18-Jul-12 7:59
andrewhelgeland18-Jul-12 7:59 
This would be really helpful for me too. Even though this is a pretty old post, maybe someone could look in to this?
Generalconsuming webservice using jquery Pin
Rajendra Malav15-Feb-10 4:15
Rajendra Malav15-Feb-10 4:15 
GeneralGreat Exemple but... works fine on firefox but not on ie:( Pin
Nezz Ramos21-Jan-10 1:59
Nezz Ramos21-Jan-10 1:59 
GeneralRe: Great Exemple but... works fine on firefox but not on ie:( Pin
Alexandru Cibotari9-Feb-10 5:11
Alexandru Cibotari9-Feb-10 5:11 
QuestionThanks a lot for the example, but a question... Pin
sognant13-Dec-09 15:32
sognant13-Dec-09 15:32 
NewsSuggestion Pin
Abi Bellamkonda30-Nov-09 13:40
Abi Bellamkonda30-Nov-09 13:40 

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.