Consume an ASP.NET WebService returning List<> with Dates using jQuery

Posted by: Suprotim Agarwal , on 5/21/2009, in Category jQuery and ASP.NET
Views: 73455
Abstract: In this article, we will see how to consume an ASP.NET WebService using jQuery. I will be demonstrating how to consume a .NET List<> returning Date fields via a .NET webservice, using jQuery. JSON does not handle dates well and we will see how the jMSAjax plug-in helps us solve the date problem.
Consume an ASP.NET WebService returning List<> with Dates using jQuery
In this article, we will see how to consume an ASP.NET WebService using jQuery. I will be demonstrating how to consume a .NET List<> returning Date fields via a .NET webservice, using jQuery. We will be using both the jQuery.ajax ($.ajax) and the jMSAjax plug-in to retrieve data from an ASP.NET WebService. JSON does not handle dates well and we will see how the jMSAjax plug-in supports ASP.NET Date formatting.
Note: I assume you are familiar with jQuery. If you are new to jQuery, then before moving ahead, I would recommend you to check out Using jQuery with ASP.NET - A Beginner's Guide. Please do take a note that this article uses jQuery’s current version - jQuery 1.3.2 and jQuery 1.3.2 Visual Studio 2008 Autocomplete documentation.
Let’s create our webservice first.
Step 1: Open Visual Studio 2008 > File > New > WebSite > Give it a name and location and click OK.
Step 2: Now right click the project in the Solution Explorer > Add New Item > Select WebService from the templates > Give it a name ‘EmployeeList.asmx’ and click on Add.
Step 3: A code file gets created in the App_Code directory. The default code for the WebService contains a ‘Hello World’ method. Remove the method and replace it with our own method that will retrieve Employee details from the Northwind database. The code will look similar to the following:
using System;
using System.Collections.Generic;
using System.Web.Services;
using System.Web.Script.Services;
using System.Data.SqlClient;
using System.Data;
/// Summary description for EmployeeList
[WebService(Namespace = "")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
public class EmployeeList : System.Web.Services.WebService {
    public EmployeeList () {
        //Uncomment the following line if using designed components
    [ScriptMethod(UseHttpGet = false, ResponseFormat = ResponseFormat.Json)]
    public List<Employee> GetEmployees()
        string nwConn = System.Configuration.ConfigurationManager.ConnectionStrings["NorthwindConnectionString"].ConnectionString;
        var empList = new List<Employee>();
        using (SqlConnection conn = new SqlConnection(nwConn))
            const string sql = @"SELECT TOP 10 FirstName, LastName, Title, BirthDate FROM Employees";
            using (SqlCommand cmd = new SqlCommand(sql, conn))
                SqlDataReader dr = cmd.ExecuteReader(
                if (dr != null)
                    while (dr.Read())
                        var emp = new Employee
                            FirstName = dr.GetString(0),
                            LastName = dr.GetString(1),
                            Title = dr.GetString(2),
                            BirthDate = dr.GetDateTime(3)
                return empList;
public class Employee
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string Title { get; set; }
    public DateTime BirthDate { get; set; }
Imports System.Web
Imports System.Web.Services
Imports System.Web.Services.Protocols
Imports System.Web.Script.Services
Imports System.Data.SqlClient
Imports System.Data
' To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
<System.Web.Script.Services.ScriptService()> _
<WebService(Namespace:="")> _
<WebServiceBinding(ConformsTo:=WsiProfiles.BasicProfile1_1)> _
<Global.Microsoft.VisualBasic.CompilerServices.DesignerGenerated()> _
Public Class EmployeeList
    Inherits System.Web.Services.WebService
    <ScriptMethod(UseHttpGet:=False, ResponseFormat:=ResponseFormat.Json), WebMethod()> _
    Public Function GetEmployees() As List(Of Employee)
        Dim nwConn As String = System.Configuration.ConfigurationManager.ConnectionStrings("NorthwindConnectionString").ConnectionString
        Dim empList = New List(Of Employee)()
        Using conn As New SqlConnection(nwConn)
            Const sql As String = "SELECT TOP 10 FirstName, LastName, Title, BirthDate FROM Employees"
            Using cmd As New SqlCommand(sql, conn)
                Dim dr As SqlDataReader = cmd.ExecuteReader(CommandBehavior.CloseConnection)
                If dr IsNot Nothing Then
                    Do While dr.Read()
                        Dim emp = New Employee With {.FirstName = dr.GetString(0), .LastName = dr.GetString(1), .Title = dr.GetString(2), .BirthDate = dr.GetDateTime(3)}
                End If
                Return empList
            End Using
        End Using
    End Function
End Class
Public Class Employee
    Private privateFirstName As String
    Public Property FirstName() As String
            Return privateFirstName
        End Get
        Set(ByVal value As String)
            privateFirstName = value
        End Set
    End Property
    Private privateLastName As String
    Public Property LastName() As String
            Return privateLastName
        End Get
        Set(ByVal value As String)
            privateLastName = value
        End Set
    End Property
    Private privateTitle As String
    Public Property Title() As String
            Return privateTitle
        End Get
        Set(ByVal value As String)
            privateTitle = value
        End Set
    End Property
    Private privateBirthDate As DateTime
    Public Property BirthDate() As DateTime
            Return privateBirthDate
        End Get
        Set(ByVal value As DateTime)
            privateBirthDate = value
        End Set
    End Property
End Class
As you can observe in the code above, we are instantiating a List<Employee> and then using the DataReader to populate the list. We then return this list to the calling function. A very important point to observe is that our method is decorated with the [ScriptMethod(UseHttpGet = false, ResponseFormat = ResponseFormat.Json)] which enables the response to be serialized as a JSON string, also making it AJAX friendly. Personally, I think this attribute is way cool since it enables my runtime to deliver  JSON objects, without me getting into any JSON transformation nitty-gritty’s.
The web.config file will have an entry for the connectionstring similar to the following:
    <add name="NorthwindConnectionString" connectionString="Data Source=(local);Initial Catalog=Northwind;Integrated Security=True"/>
With our webservice ready, our first approach will involve retrieving data using the $.ajax method and observe the shortcomings of JSON objects while expressing fields like Date.
Step 4: Go to your Default.aspx and add the following jQuery code to retrieve data from the ASP.NET WebService using $.ajax method
<head runat="server">
    <title>Access ASP.NET WebService using jQuery</title>
    <script src="Scripts/jquery-1.3.2.js" type="text/javascript"></script>
    <script type="text/javascript">
        $(document).ready(function() {
                type: "POST",
                url: "EmployeeList.asmx/GetEmployees",
                data: "{}",
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function(list) {
                    $("#Something").append("<ul id='bullets'></ul>");
                    for (i = 0; i < list.d.length; i++) {
                        $("#bullets").append("<li>" + list.d[i].FirstName
                        + " : " + list.d[i].LastName + " : " + list.d[i].BirthDate + "</li>");
                error: function(e) {
                    $("#Something").html("There was an error retrieving records");
    <form id="form1" runat="server">
    <div id="Something">
On running your application, you will get an output similar to the following:
 As you can observe in the screenshot, the dates are not being handled well in JSON. The DateTime is serialized as an escaped JavaScript Date initializer - /Date(-124003800000)/. Dave Ward has explained this behavior quite well on his blog. You can also find some information on this behavior at schotime’s blog, the creator of the jMSAjax plug-in.
Note: To call a remote webservice, check this technique described by Jason
Resolving the JSON Date formatting
Enter the jMSAjax plug-in! The jMSAjax plug-in adds additional capabilities to the existing $.ajax to support ASP.NET Date formatting and resolve other shortcomings. It also does not require you to access the ‘d’ property (like we did while using $.ajax) to access data. Additional advantages are listed here.
To use this plug-in, first download the jMSAjax plug-in over here. Then add a reference to this file in the <head> section of your page. Here’s how to use the jMSAjax plug-in to access a JSON Serialized List<> returning Date objects.
<html xmlns="">
<head runat="server">
    <title>Access ASP.NET WebService using jQuery</title>
    <script src="Scripts/jquery-1.3.2.js" type="text/javascript"></script>
    <script src="Scripts/jquery.jmsajax.js" type="text/javascript"></script>
    <script type="text/javascript">
        $(document).ready(function() {
                url: "EmployeeList.asmx",
                method: "GetEmployees",
                dataType: "msjson",
                success: function(list) {
                    $("#Something").append("<br/><ul id='bullets'></ul>");
                    for (i = 0; i < list.length; i++) {
                        $("#bullets").append("<li>" + list[i].FirstName
                        + " : " + list[i].LastName + " : " + list[i].BirthDate + "</li>");
                error: function(e) {
                    $("#Something").html("There was an error retreiving records");
    <form id="form1" runat="server">
    <div id="Something">
The output of the application is shown below.
As you can observe, the dates returned by JSON are well formatted now! Way cool and a great plug-in by Schotime!
I hope this article was useful and I thank you for viewing it. The entire source code of this article can be downloaded from here

This article has been editorially reviewed by Suprotim Agarwal.

Absolutely Awesome Book on C# and .NET

C# and .NET have been around for a very long time, but their constant growth means there’s always more to learn.

We at DotNetCurry are very excited to announce The Absolutely Awesome Book on C# and .NET. This is a 500 pages concise technical eBook available in PDF, ePub (iPad), and Mobi (Kindle).

Organized around concepts, this Book aims to provide a concise, yet solid foundation in C# and .NET, covering C# 6.0, C# 7.0 and .NET Core, with chapters on the latest .NET Core 3.0, .NET Standard and C# 8.0 (final release) too. Use these concepts to deepen your existing knowledge of C# and .NET, to have a solid grasp of the latest in C# and .NET OR to crack your next .NET Interview.

Click here to Explore the Table of Contents or Download Sample Chapters!

What Others Are Reading!
Was this article worth reading? Share it with fellow developers too. Thanks!
Share on LinkedIn
Share on Google+

Suprotim Agarwal, MCSD, MCAD, MCDBA, MCSE, is the founder of DotNetCurry, DNC Magazine for Developers, SQLServerCurry and DevCurry. He has also authored a couple of books 51 Recipes using jQuery with ASP.NET Controls and The Absolutely Awesome jQuery CookBook.

Suprotim has received the prestigious Microsoft MVP award for ten consecutive times. In a professional capacity, he is the CEO of A2Z Knowledge Visuals Pvt Ltd, a digital group that offers Digital Marketing and Branding services to businesses, both in a start-up and enterprise environment.

Get in touch with him on Twitter @suprotimagarwal or at LinkedIn

Page copy protected against web site content infringement 	by Copyscape

Feedback - Leave us some adulation, criticism and everything in between!
Comment posted by anup hosur on Thursday, May 21, 2009 9:36 AM
nice article bro..
Comment posted by Harikrishnan on Tuesday, May 26, 2009 1:52 AM
Hello this is working while we using aspx page and update panel...And after i added this script code in a usercontrol and update panel.. Not workig..Any idea about tis.if yes pls frwd the answer.     Hari eis triandrum
Comment posted by shimpark on Thursday, May 28, 2009 12:52 PM
nice article
Comment posted by Sheeban on Thursday, July 16, 2009 6:18 AM
I have a problem with when i try to put where clause in to the sql query?
how can we pass textbox value with the help of JQuery to the EmployeeList Class
Comment posted by Deepak Chawla on Tuesday, July 21, 2009 6:18 AM
This article has a fundamental problem.
Managing change in day light time change. i.e. Summer time which is one hour ahead of normal time.

So now for the bugs in the above code
Server side:
BirthDate = dr.GetDateTime(3)
needs to be replaced with
BirthDate = new DateTime(db.getDateTime(3).Year, etc etc for month day, DateTimeKind.UTC) ;

This DateTimeKind keeps the same value to the browser as sent by the server.

Client Side:
Please search for JSON2 script. and download it from

The client on success function should be more like

success: function(list) {
   var responseObjects = JSON2.parse (list);
   etc. etc.

This would create an object collection and then use standard function to traverse and display.

This is such an old way of returning via JSON format I think I wrote the same on Scott Guthrie blogs more than 2-3 year ago.

New world is using MVC and return JSONResult as response.

Comment posted by zmeun on Tuesday, July 21, 2009 8:54 PM
it was nice article.. thanks
Comment posted by sandesh on Tuesday, October 6, 2009 3:06 AM

I have wriiten a JQuery where I can move items form one Listbox to another and its working fine, when I do a postback ie when I click a Asp server side button the listbox with populated items using Jquery disappears… How can i avoid this
Comment posted by zeynel coşgun on Monday, March 28, 2011 4:19 PM
thank u so was helpful.
Comment posted by SVK on Saturday, September 17, 2011 3:50 AM
how culd the same be implemented without jason
Comment posted by Prerna Gupta on Friday, January 25, 2013 5:01 AM
very very helpful :) many many thanks
Comment posted by Zeeshan on Friday, June 21, 2013 5:27 AM
Hey, You just did not save my time you have saved my job :D
Comment posted by Sanjay Patel on Tuesday, March 17, 2015 2:10 AM
Thank this is help full.
Comment posted by SANDEEP KAUSHIK on Sunday, April 12, 2015 4:29 PM
while i am trying to consume webservice to shows error ...  it is working fine in asp web form code behind ... but i dont know wht is the problem. i dont have any idea about authorization .. plzz help
Comment posted by mohamadreza on Saturday, May 30, 2015 5:56 PM
thanks alot it was very nice






jQuery CookBook