使用DataTable将数据库数据从服务器传递到客户端

时间:2013-04-15 15:46:17

标签: c# json serialization gridview

我有以下服务器代码:

Methods.cs

public DataTable GetAllCreditCards()
        {
            string connStr = ConfigurationManager.ConnectionStrings["BankDB"].ConnectionString;
            SqlConnection conn = new SqlConnection(connStr);
            SqlDataAdapter adapter = new SqlDataAdapter();
            DataTable data_table = new DataTable();
            conn.Open();

            SqlCommand cmd = new SqlCommand("GetAllAccountDetails", conn);
            cmd.CommandType = CommandType.StoredProcedure;
            adapter.SelectCommand = cmd;
            adapter.Fill(data_table);
            conn.Close();
            return data_table;
        }

Handler.ashx

if (function.Equals("GetAllCreditCards"))
            {
                DataTable text = m.GetAllCreditCards();

                System.Web.Script.Serialization.JavaScriptSerializer oSerializer = new System.Web.Script.Serialization.JavaScriptSerializer();
                string json = oSerializer.Serialize(text);

                context.Response.Write(json);
            }

我有以下客户端代码:

HomePage.aspx

if (TextBox_Function.Text.Equals("GetAllCreditCards"))
            {
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://localhost:4000/Handler.ashx?function=" + TextBox_Function.Text);
                HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                String answer = returnResponse(response);

                System.Web.Script.Serialization.JavaScriptSerializer oSerializer = new System.Web.Script.Serialization.JavaScriptSerializer();
                DataTable data_table = oSerializer.Deserialize<DataTable>(answer);

                Session["data_table"] = data_table;
                Response.Redirect("Results_Reader.aspx");
            }

Results_Reader.aspx

protected void Page_Load(object sender, EventArgs e)
{
    DataTable data_table = (DataTable)Session["data_table"];
    GridView_DataTable.DataSource = data_table;
    GridView_DataTable.DataBind();
}

我要做的是从服务器获取数据库数据,将其放入数据表,将数据表发送到客户端并将该数据表绑定到网格视图。

当我尝试运行客户端并在变量函数中输入“GetAllCreditCards”时,服务器项目会出现以下错误:

A circular reference was detected while serializing an object of type 'System.Reflection.RuntimeModule'.

我做错了什么?我只想传递数据库数据并将其绑定到客户端的网格视图,这就是全部。

修改

似乎JavaScriptSerializer无法序列化数据表。那么如何将记录从服务器发送到客户端并将它们绑定到网格视图?

1 个答案:

答案 0 :(得分:1)

我的猜测是,您正在进行的javascript序列化存在问题,请查看此处是否有帮助A circular reference was detected while serializing an object of type 'SubSonic.Schema .DatabaseColumn'.