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

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

, 27 Nov 2009
Rate this:
Please Sign up or sign in to vote.
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:

<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.

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:

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:

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:

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:

    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)

About the Author

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

Comments and Discussions

 
Question500 Error When i write <httphandlers> Pinmembergkaradagan12-Mar-13 8:42 
AnswerRe: 500 Error When i write <httphandlers> PinmemberHSU_050427-Mar-13 16:08 
QuestionCross-Domain? Pinmemberandrewhelgeland18-Jul-12 8:01 
GeneralMy vote of 5 PinmemberMd. Humayun Rashed17-Jun-12 1:20 
QuestionError Pinmembernatarajangovindavel10-Apr-12 22:08 
AnswerRe: Error PinmemberMember 893111825-Mar-14 12:48 
QuestionI´ve got an Error Pinmemberyellow_lucky26-Jan-12 2:41 
Questiongreat example, but still xml format Pinmemberxin gong27-Dec-11 10:02 
AnswerRe: great example, but still xml format Pinmemberxin gong27-Dec-11 10:07 
AnswerRe: great example, but still xml format Pinmembernatarajangovindavel10-Apr-12 22:02 
GeneralMy vote of 1 PinmemberMember 79268046-Oct-11 22:04 
Questionwhere is the code behind file? Pinmemberjeyanth22-Aug-11 7:46 
GeneralMy vote of 1 PinmemberAshish Sharma11-Feb-11 18:47 
GeneralSome changes to make it work. Pinmemberthomasa26-Nov-10 5:23 
GeneralGreat example but what about cross domain PinmemberSuper Boss30-Apr-10 13:23 
GeneralRe: Great example but what about cross domain Pinmemberandrewhelgeland18-Jul-12 7:59 
Generalconsuming webservice using jquery Pinmemberrajendra malav15-Feb-10 4:15 
GeneralGreat Exemple but... works fine on firefox but not on ie:( PinmemberNezz Ramos21-Jan-10 1:59 
GeneralRe: Great Exemple but... works fine on firefox but not on ie:( PinmemberAlexandru Cibotari9-Feb-10 5:11 
It worked in IE and Firefox for me
QuestionThanks a lot for the example, but a question... Pinmembersognant13-Dec-09 15:32 
NewsSuggestion PinmemberAbishek Bellamkonda30-Nov-09 13:40 
GeneralRe: Suggestion PinmemberAjay Singh30-Nov-09 20:32 
GeneralRe: Suggestion Pinmemberjpeterson29-Mar-10 9:37 
GeneralRe: Suggestion PinmemberAbishek Bellamkonda29-Mar-10 9:57 

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.140709.1 | Last Updated 28 Nov 2009
Article Copyright 2009 by Ajay Singh
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid