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:
When you return data in JSON format, you will get something like this:
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:
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.
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:
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:
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
{
[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)
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:
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.