'undefined' reported when bind gridview using AJAX in C#

痴心易碎 提交于 2019-12-13 17:19:44

问题


I want to bind the gridview using AJAX. So, for that I done client side code using AJAX and server side code as a webmethod.

Everything is working fine even I alert the data in success method at that time also data is showing but in loop I really confused that it is showing undefined in alert. So for that's why grid is not binding.

Here is my code

$.ajax({
    type: "POST",
    url: "schoolregistration.aspx/GetGridData",
    contentType: "application/json; charset=utf-8",
    datatype: "json",
    success: function (data) {
        for (var i = 0; i < data.d.length; i++) {
            $("#grid_schooldata").append("<tr><td>" + data.d[i].schoolName);
        }
    },
    failure: function () {
        alert("error! try again...");
    }
});

 

using (var con = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString))
using (var cmd = new SqlCommand("select schoolname as [School Name] from tbl_schoolregistration", con))
{
    con.Open();
    object val = cmd.ExecuteScalar();
    return val == DBNull.Value ? "" : (string)val;
}

回答1:


First of all

ExecuteScalar Executes the query, and returns the first column of the first row in the result set returned by the query. Additional columns or rows are ignored.

In this case you will have a single string.

Secondly beware of the name in your query leave it as schoolname not [School Name].

Then you have to Serialize into json and again parse into json in order to loop through objects.

Here is fully working code:

$.ajax({
    type: "POST",
    url: "schoolregistration.aspx/GetGridData",
    contentType: "application/json; charset=utf-8",
    datatype: "json",
    success: function (data) {
        data = JSON.parse(data.d);
        for (var i = 0; i < data.length; i++) {
          $("#grid_schooldata").append("<tr><td>" + data[i].schoolname +"</td></tr>");      
        }
    },
    failure: function () {
        alert("error! try again...");
    }
});



[WebMethod]
public static string GetGridData()
{
    using (var con = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString))
    using (var cmd = new SqlCommand("select schoolname from tbl_schoolregistration", con))
    {
        con.Open();
        //object val = cmd.ExecuteScalar();
        SqlDataAdapter adp = new SqlDataAdapter(cmd);
        DataTable dt = new DataTable();
        adp.Fill(dt); // fills data from select query

        // return val == DBNull.Value ? "" : (string)val;
        return JsonConvert.SerializeObject(dt);
    }
}


来源:https://stackoverflow.com/questions/44992714/undefined-reported-when-bind-gridview-using-ajax-in-c-sharp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!