Shalvin Interests

Tuesday, March 29, 2016

JQuery Ajax : Consuming Array of JSON

In this blog I am going to demonstrate consuming a Web Service which exposes the data from a table as JSON.



public class Contacts
{
    public int ContactId { get; set; }
    public string ContactName { get; set; }
    public string Email { get; set; }
    public string Phone { get; set; }
}

using System;
using System.Collections.Generic;
using System.Web.Services;
using System.Data.SqlClient;
using System.Web.Script.Serialization;

/// <summary>
/// Summary description for WebService
/// </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 WebService : System.Web.Services.WebService {

    public WebService () {

        //Uncomment the following line if using designed components 
        //InitializeComponent(); 
    }

    [WebMethod]
    public void GetContacts() {
        List<Contacts> glCG = new List<Contacts>();

        SqlConnection cnn = new SqlConnection(@"Data Source=.\sqlexpress;Initial Catalog=SimpleContactManagement;Integrated Security=True");
        cnn.Open();
        SqlCommand cmd = new SqlCommand("select * from Contacts", cnn);
        SqlDataReader dr = cmd.ExecuteReader();

        while(dr.Read())
        {
            int intConId = Int32.Parse(dr["ContactId"].ToString());
            Contacts c = new Contacts
            {
                ContactId = intConId,
                ContactName = dr["ContactName"].ToString(),
                Email = dr["Email"].ToString(),
               Phone = dr["Phone"].ToString()
            };
            glCG.Add(c);
        }

        JavaScriptSerializer sc = new JavaScriptSerializer();
        Context.Response.Write(sc.Serialize(glCG));
    }
    
}


<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title></title>
    <script src="Scripts/jquery-1.12.1.js"></script>
    <script>
        $(document).ready(function () {
            getData();
        });

        function getData()
        {
            $.ajax(
                {
                    url: 'WebService.asmx/GetContacts',
                    dataType: "json",
                    method: 'post',
                    success: function (data) {
                        var contactsTable = $('#tblContacts tbody');
                        contactsTable.empty();

                        $(data).each(function (index, con) {
                            contactsTable.append('<tr><td>' + con.ContactId +
                                '</td><td>' + con.ContactName +
                                '</td><td>' + con.Email +
                                '</td><td>' + con.Phone +
                                '</td></tr>');
                        });
                    }
                });

            }
    </script>
</head>
<body>
    <table id="tblContacts">
        <thead>
            <tr>
                <th>Id</th>
                <th>Name</th>
                <th>Email</th>
                <td>Phone</td>
            </tr>
         </thead>
        <tbody>

        </tbody>
    </table>
</body>
</html>



No comments:

Post a Comment