JQuery - Consumir um Webservice em ASPNET retornando List<> com Data

<< Click to Display Table of Contents >>

Navigation:  jQuery >

JQuery - Consumir um Webservice em ASPNET retornando List<> com Data

Previous pageReturn to chapter overviewNext page

Código do Webservice

 

EmployeeList.asmx

 

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; }
}

 

 

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.

 

Default.aspx

 

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>

 

Resultado

 

Unformatted_Date

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>

 

Retorno

 

Formatted_Date_UsingjMSAjax_Plugin