Handling JSON Arrays Returned From ASP.NET Web Services With jQuery

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Configuration;  
  4. using System.Data;  
  5. using System.Linq;  
  6. using System.Text;  
  7. using System.Text.RegularExpressions;  
  8. using System.Web;  
  9. using System.Web.Script.Serialization;  
  10. using System.Web.Script.Services;  
  11. using System.Web.Services;  
  12. namespace VIS {  
  13.     [WebService(Namespace = "http://tempuri.org/")]  
  14.     [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]  
  15.     [System.ComponentModel.ToolboxItem(false)]  
  16.     // To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.  
  17.     [System.Web.Script.Services.ScriptService]  
  18.     public class WebMyService: System.Web.Services.WebService {  
  19.         string connetionString = null;  
  20.         SqlConnection sqlCnn;  
  21.         SqlCommand sqlCmd;  
  22.         SqlDataAdapter adapter = new SqlDataAdapter();  
  23.         DataSet dsbind = new DataSet();  
  24.         int i = 0;  
  25.         string sql = null;  
  26.         public class Gender {  
  27.             public string employeeid {  
  28.                 get;  
  29.                 set;  
  30.             }  
  31.             public string male {  
  32.                 get;  
  33.                 set;  
  34.             }  
  35.             public string female {  
  36.                 get;  
  37.                 set;  
  38.             }  
  39.         }  
  40.         public string JSONConversion(DataTable dt) {  
  41.                 DataSet ds = new DataSet();  
  42.                 ds.Merge(dt);  
  43.                 StringBuilder JsonString = new StringBuilder();  
  44.                 JsonString.Append("{");  
  45.                 JsonString.Append("\"Data\"");  
  46.                 JsonString.Append(":");  
  47.                 if (ds != null && ds.Tables[0].Rows.Count > 0) {  
  48.                     JsonString.Append("[");  
  49.                     for (int i = 0; i < ds.Tables[0].Rows.Count; i++) {  
  50.                         JsonString.Append("{");  
  51.                         for (int j = 0; j < ds.Tables[0].Columns.Count; j++) {  
  52.                             if (j < ds.Tables[0].Columns.Count - 1) {  
  53.                                 JsonString.Append("\"" + ds.Tables[0].Columns[j].ColumnName.ToString() + "\":" + "\"" + ds.Tables[0].Rows[i][j].ToString() + "\",");  
  54.                             } else if (j == ds.Tables[0].Columns.Count - 1) {  
  55.                                 JsonString.Append("\"" + ds.Tables[0].Columns[j].ColumnName.ToString() + "\":" + "\"" + ds.Tables[0].Rows[i][j].ToString() + "\"");  
  56.                             }  
  57.                         }  
  58.                         if (i == ds.Tables[0].Rows.Count - 1) {  
  59.                             JsonString.Append("}");  
  60.                         } else {  
  61.                             JsonString.Append("},");  
  62.                         }  
  63.                     }  
  64.                     JsonString.Append("]");  
  65.                     JsonString.Append("}");  
  66.                     return JsonString.ToString();  
  67.                 } else {  
  68.                     return null;  
  69.                 }  
  70.             }  
  71.             [WebMethod]  
  72.             [ScriptMethod(ResponseFormat = ResponseFormat.Json)]  
  73.         public Gender[] GenderWise() {  
  74.             connetionString = "Data Source=ServerName;Initial Catalog=DatabaseName;User ID=UserName;Password=Password";  
  75.             sql = "select distinct(empid) as employeeid, count(case when gender='M' then 1 end) as Male, count(case when gender='F' then 1 end) as Female from V_CountOnGender";  
  76.             sqlCnn = new SqlConnection(connetionString);  
  77.             try {  
  78.                 sqlCnn.Open();  
  79.                 sqlCmd = new SqlCommand(sql, sqlCnn);  
  80.                 adapter.SelectCommand = sqlCmd;  
  81.                 adapter.Fill(dsbind);  
  82.                 JavaScriptSerializer obj = new JavaScriptSerializer();  
  83.                 string result = string.Empty;  
  84.                 Gender[] arrlst = new Gender[dsbind.Tables[0].Rows.Count];  
  85.                 if (dsbind.Tables[0].Rows.Count > 0) {  
  86.                     for (int i = 0; i < dsbind.Tables[0].Rows.Count; i++) {  
  87.                         Gender objgender = new Gender();  
  88.                         objgender.employeeid = dsbind.Tables[0].Rows[i]["employeeid"].ToString();  
  89.                         objgender.male = dsbind.Tables[0].Rows[i]["Male"].ToString();  
  90.                         objgender.female = dsbind.Tables[0].Rows[i]["Female"].ToString();  
  91.                         arrlst.SetValue(objgender, i);  
  92.                     }  
  93.                 } else {  
  94.                     result = "No Record Found";  
  95.                 }  
  96.             } catch (Exception ex) {}  
  97.             return arrlst;;  
  98.         }  
  99.     }  
  100. }  
  101. This will go into the < head > section of the page:  
  102.     <  
  103.     script type = "text/javascript"  
  104. src = "script/jquery-1.2.6.min.js" > < /script> <  
  105.     script type = "text/javascript" >  
  106.     $(document).ready(function() {  
  107.         $.ajax({  
  108.             type: "POST",  
  109.             contentType: "application/json; charset=utf-8",  
  110.             dataType: "json",  
  111.             url: "/WebMyVoterService.asmx/GenderWise",  
  112.             processData: false,  
  113.             success: OnSuccess,  
  114.             failure: function(response) {  
  115.                 alert("Can't be able to bind graph");  
  116.             },  
  117.             error: function(response) {  
  118.                 alert("Can't be able to bind graph");  
  119.             }  
  120.         });  
  121.   
  122.         function OnSuccess(response) {  
  123.             var dpmale = [];  
  124.             var dpfemale = [];  
  125.             for (var i = 0; i < response.d.length; i++) {  
  126.                 var obj = response.d[i];  
  127.                 var datamale = {  
  128.                     y: parseInt(obj.male),  
  129.                     label: obj.employeeid,  
  130.                 };  
  131.                 var datafemale = {  
  132.                     y: parseInt(obj.female),  
  133.                     label: obj.employeeid,  
  134.                 };  
  135.                 dpmale.push(datamale);  
  136.                 dpfemale.push(datafemale);  
  137.             }  
  138.             var chart = new CanvasJS.Chart("chartContainerbar", {  
  139.                 animationEnabled: true,  
  140.                 axisX: {  
  141.                     interval: 1,  
  142.                     labelFontSize: 10,  
  143.                     lineThickness: 0,  
  144.                 },  
  145.                 axisY2: {  
  146.                     valueFormatString: "0",  
  147.                     lineThickness: 0,  
  148.                     labelFontSize: 10,  
  149.                 },  
  150.                 toolTip: {  
  151.                     shared: true  
  152.                 },  
  153.                 legend: {  
  154.                     verticalAlign: "top",  
  155.                     horizontalAlign: "center",  
  156.                     fontSize: 10,  
  157.                 },  
  158.                 data: [{  
  159.                     type: "stackedBar",  
  160.                     showInLegend: true,  
  161.                     name: "Male",  
  162.                     axisYType: "secondary",  
  163.                     color: "#f8d347",  
  164.                     dataPoints: dpmale  
  165.                 }, {  
  166.                     type: "stackedBar",  
  167.                     showInLegend: true,  
  168.                     name: "Female",  
  169.                     axisYType: "secondary",  
  170.                     color: "#6ccac9",  
  171.                     dataPoints: dpfemale  
  172.                 }]  
  173.             });  
  174.             chart.render();  
  175.         }  
  176.     }); <  
  177. /script>