Click here to Skip to main content
15,886,362 members
Please Sign up or sign in to vote.
4.00/5 (1 vote)
See more:
I have an aspx page and i am fetching data in code behind from Oracle DB and getting it in a DataTable.

In the aspx, I plan to use JavaScript to retrieve the DataTable from the .cs file. Any good reference for doing this? Thanks in advance.
Posted
Updated 5-Aug-14 18:46pm
v2

Here is my example to explain your scenario :-

1) Include the following references as mentioned below in the code behind :-
C#
using System;
using System.Collections.Generic;
using System.Data;
using System.Web.Script.Serialization;
using System.Web.Services;


2) Created a new test data table for the fetching of data on page load as below :-
C#
protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                _dt.Columns.Add("ID");
                _dt.Columns.Add("Name");
                
                DataRow dr1 = _dt.NewRow();
                dr1["ID"] = 1;
                dr1["Name"] = "Smruti";
                _dt.Rows.Add(dr1);

                DataRow dr2 = _dt.NewRow();
                dr2["ID"] = 2;
                dr2["Name"] = "Ranjan";
                _dt.Rows.Add(dr2);
            }
        }


3) Create a page method to return data from this DataTable in JSON formatted string as below :-

C#
[WebMethod]
        public static string GetData()
        {
            List<Dictionary<string, object>> dicRows = new List<Dictionary<string, object>>();
            Dictionary<string, object> dicRow = null;
            foreach (DataRow dr in _dt.Rows)
            {
                dicRow = new Dictionary<string, object>();
                foreach (DataColumn col in _dt.Columns)
                {
                    dicRow.Add(col.ColumnName, dr[col]);
                }
                dicRows.Add(dicRow);
            }

            JavaScriptSerializer objSerializer = new JavaScriptSerializer();
            string sJSON = objSerializer.Serialize(dicRows);
            return sJSON;
        }


4) Now in aspx page add a reference to JS file & code to call the 'GetData' method through jQuery Ajax inside the head as below :-

XML
<head runat="server">
    <title></title>
    <script src="jquery-2.0.3.js"></script>
    <script type="text/javascript">

        $(function () {
            $("#btnTest").click(function () {
                GetTestData();
            });
        });

        function GetTestData() {
            $.ajax({
                type: "POST",
                url: "../DataTableTestWithJQuery.aspx/GetData",
                data: "{}",
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                async: false,
                success: function (response) {
                    var result = JSON.parse(response.d);
                    $.each(result, function (index, obj) {
                        alert(obj.ID);
                        alert(obj.Name);
                    });
                },
                error: function (XMLHttpRequest, textStatus, errorThrown) {
                    alert(errorThrown);
                }
            });
        }

    </script>
</head>


In the similar way you can get your Oracle DB data fetched as DataTable in client-side code in aspx.

Hope this will definitely of help to you.
 
Share this answer
 
v2
try this.. :)

html

1) Index.aspx

HTML
<html xmlns="http://www.w3.org/1999/xhtml">
<head  runat="server">
    <title></title>
    <script src="http://code.jquery.com/jquery-1.11.1.min.js">
    type="text/javascript"></script>
    <script type="text/javascript">

        $(document).ready(function () {
            BindGridView();

        });

        function BindGridView() {

            $.ajax({
                type: "POST",
                url: "Index.aspx/GetData",
                contentType: "application/json;charset=utf-8",
                data: {},
                dataType: "json",
                success: function (data) {

                    $("#grdDemo").empty();

                    if (data.d.length > 0) {
                        $("#grdDemo").append("<tr><th>Username</th>  
                        <th>Firstname</th>  <th>Lastname</th>  
                        <th>EmailID</th></tr>");
                        for (var i = 0; i < data.d.length; i++) {

                            $("#grdDemo").append("<tr><td>" + 
                            data.d[i].Firstname + "</td> <td>" + 
                            data.d[i].Lastname + "</td> <td>" + 
                            data.d[i].Username + "</td> <td>" + 
                            data.d[i].EmailID + "</td></tr>");
                        }
                    }
                },
                error: function (result) {
                    //alert("Error login");

                }
            });
        }
    </script>
</head>
<body>
    <form id="frm1"  runat="server">
    <asp:gridview id="grdDemo" runat="server" xmlns:asp="#unknown">
    </asp:gridview>
    </form>
</body>
</html> 


CS Page

C#
protected void Page_Load(object sender, EventArgs e)
        {
            BindDummyItem(); //Bind dummy datatable to grid view to bind data in it.
        }
        public void BindDummyItem()
        {
            DataTable dtGetData = new DataTable();
            dtGetData.Columns.Add("Username");
            dtGetData.Columns.Add("Firstname");
            dtGetData.Columns.Add("Lastname");
            dtGetData.Columns.Add("EmailID");
            dtGetData.Rows.Add();

            grdDemo.DataSource = dtGetData;
            grdDemo.DataBind();
        }

        [WebMethod] 
        public static DetailsClass[] GetData() //GetData function
        {
            List<detailsclass> Detail = new List<detailsclass>();

            string SelectString = "Select Username,Firstname,Lastname,EmailID from DemoTable";
            SqlConnection cn = new SqlConnection("Data Source=servername;
            Initial Catalog=DemoDatabase;User ID=User;Password=*****");
            SqlCommand cmd = new SqlCommand(SelectString,cn);
            cn.Open();

            SqlDataAdapter da = new SqlDataAdapter(cmd);
            DataTable dtGetData = new DataTable();

            da.Fill(dtGetData);

            foreach(DataRow dtRow in dtGetData.Rows)
            {
                DetailsClass DataObj = new DetailsClass();
                DataObj.Username = dtRow["Username"].ToString();
                DataObj.Firstname = dtRow["Firstname"].ToString();
                DataObj.Lastname = dtRow["Lastname"].ToString();
                DataObj.EmailID = dtRow["EmailID"].ToString();

                Detail.Add(DataObj);            
            }

            return Detail.ToArray();
        }
        public class DetailsClass //Class for binding data
        {
            public string Username { get; set; }
            public string Firstname { get; set; }
            public string Lastname { get; set; }
            public string EmailID { get; set; }
        
        }


for more info.. :)

Bind Gridview using AJAX[^]
 
Share this answer
 
v2
Comments
s yu 6-Aug-14 15:39pm    
Nirav: Thanks for your response. I created an aspx and pasted your code w/ minor customization. But I got a couple of errors and warnings. E.g. for
List<detailsclass> Detail = new List<detailsclass>();
Error: detailsclass could not be found. Could you point out what's wrong in my application? Thanks.
Nirav Prabtani 7-Aug-14 0:30am    
public class DetailsClass //Class for binding data
{
public string Username { get; set; }
public string Firstname { get; set; }
public string Lastname { get; set; }
public string EmailID { get; set; }

}

this is detailsclass
s yu 7-Aug-14 7:47am    
Thanks. Went thru. after changing detailsclass to DetailsClass.
Nirav Prabtani 7-Aug-14 8:00am    
welcome.. :)

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900