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.
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:
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.
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.
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!
Was this article worth reading? Share it with fellow developers too. Thanks!
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