How to return a DataTable from WebMethod using JSON and JQuery in asp.net?

I am new to JSON . I created a sample that returns a String from WebMethod and assigns the value returned to the asp.net Label control.

JSON String Return Example:

 <asp:Content ID="Content1" ContentPlaceHolderID="HeadContent" Runat="Server"> <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"></script> <script type="text/javascript"> $(document).ready(function() { $.ajax({ type: "POST", contentType: "application/json; charset=utf-8", url: "JSONSample.aspx/DisplayData", data: "{}", dataType: "json", success: function(data) { //alert("hi"); $("#ctl00_MainContent_lbltxt").text(data.d); }, error: function(result) { alert("Error"); } }); }); </script> </asp:Content> <asp:Content ID="Content2" ContentPlaceHolderID="MainContent" Runat="Server"> <label id="lbltxt" runat="server"></label> </asp:Content> 

In the .cs file (return line):

 [WebMethod] public static string DisplayData() { return DateTime.Now.ToString(); } 

This works great.

How to access DataTable using JSON and JQuery ?

 [WebMethod] public static DataTable DisplayData() { DataTable dt = new DataTable(); return dt.GetData(); } 

I want to return a DataTable and bind GridView / Access to each row of the DataTable using JSON and JQuery . Please suggest me the correct Return DataTable method using JSON .

I saw some examples using handlers and some examples using WebMethod . Which one to use?

What are the advantages of one over the other.

Help rate!

+6
source share
1 answer

This is how I usually do it. I load datatable contents into a dictionary, serialize it and everything works. You can change the code to suit your needs.

  [WebMethod] public string GetQueryInfo() { String daresult = null; DataTable yourDatable = new DataTable(); DataSet ds = new DataSet(); ds.Tables.Add(yourDataTable); daresult = DataSetToJSON(ds); return daresult; } public string DataSetToJSON(DataSet ds) { Dictionary<string, object> dict = new Dictionary<string, object>(); foreach (DataTable dt in ds.Tables) { object[] arr = new object[dt.Rows.Count + 1]; for (int i = 0; i <= dt.Rows.Count - 1; i++) { arr[i] = dt.Rows[i].ItemArray; } dict.Add(dt.TableName, arr); } JavaScriptSerializer json = new JavaScriptSerializer(); return json.Serialize(dict); } 

On your aspx.

  $.ajax({ type: "POST", url: 'Webservices/GetQueryInfo', data: {}, contentType: "application/json; charset=utf-8", dataType: 'json', success: function (data) { var objdata = $.parseJSON(data.d); // now iterate through this object contents and load your gridview } }); 

There are many guides to loading the grid using java script or jquery, this will at least give you a starting point. You can find a good example here . For CRUD operations with gridview see link here

+11
source

Source: https://habr.com/ru/post/959152/


All Articles