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: 50763
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:
C#
using System;
using System.Collections.Generic;
using System.Web.Services;
using System.Web.Script.Services;
using System.Data.SqlClient;
using System.Data;
 
///<summary>
/// Summary description for EmployeeList
///</summary>
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
[System.Web.Script.Services.ScriptService]
public class EmployeeList : System.Web.Services.WebService {
 
    public EmployeeList () {
 
        //Uncomment the following line if using designed components
        //InitializeComponent();
    }
 
    [ScriptMethod(UseHttpGet = false, ResponseFormat = ResponseFormat.Json)]
    [WebMethod]
    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";
            conn.Open();
            using (SqlCommand cmd = new SqlCommand(sql, conn))
            {
                SqlDataReader dr = cmd.ExecuteReader(
                    CommandBehavior.CloseConnection);
                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)
                        };
                        empList.Add(emp);
                    }
                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; }
}
VB.NET
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:="http://tempuri.org/")> _
<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"
            conn.Open()
            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)}
                        empList.Add(emp)
                    Loop
                End If
                Return empList
            End Using
        End Using
    End Function
 
End Class
 
Public Class Employee
    Private privateFirstName As String
    Public Property FirstName() As String
        Get
            Return privateFirstName
        End Get
        Set(ByVal value As String)
            privateFirstName = value
        End Set
    End Property
    Private privateLastName As String
    Public Property LastName() As String
        Get
            Return privateLastName
        End Get
        Set(ByVal value As String)
            privateLastName = value
        End Set
    End Property
    Private privateTitle As String
    Public Property Title() As String
        Get
            Return privateTitle
        End Get
        Set(ByVal value As String)
            privateTitle = value
        End Set
    End Property
    Private privateBirthDate As DateTime
    Public Property BirthDate() As DateTime
        Get
            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:
 <connectionStrings>
    <add name="NorthwindConnectionString" connectionString="Data Source=(local);Initial Catalog=Northwind;Integrated Security=True"/>
 </connectionStrings>
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() {
            $.ajax({
                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");
                }
            });
 
           
        });
    </script>
   
</head>
<body>
    <form id="form1" runat="server">
    <div id="Something">
   
    </div>
    </form>
</body>
</html>
 
On running your application, you will get an output similar to the following:
 
Unformatted_Date
 
 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="http://www.w3.org/1999/xhtml">
<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() {
 
            $.jmsajax({
                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");
                }
            });
        });
    </script>
   
</head>
<body>
    <form id="form1" runat="server">
    <div id="Something">
   
    </div>
    </form>
</body>
</html>
 
The output of the application is shown below.
 
Formatted_Date_UsingjMSAjax_Plugin
                   
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
Give a +1 to this article if you think it was well written. Thanks!
Recommended Articles
Suprotim Agarwal, ASP.NET Architecture MVP, MCSD, MCAD, MCDBA, MCSE, is the CEO of A2Z Knowledge Visuals Pvt. He primarily works as an Architect Consultant and provides consultancy on how to design and develop .NET centric database solutions.

Suprotim is the founder and primary contributor to DotNetCurry, DNC .NET Magazine, SQLServerCurry and DevCurry. He has also written an EBook 51 Recipes using jQuery with ASP.NET Controls. and is authoring another one at The Absolutely Awesome jQuery CookBook.

Follow him on twitter @suprotimagarwal


Page copy protected against web site content infringement by Copyscape


User Feedback
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 json.org

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
Hi,

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

Post your comment
Name:  
E-mail: (Will not be displayed)
Comment:
Insert Cancel