Skip to content Skip to sidebar Skip to footer

'undefined' Reported When Bind Gridview Using Ajax In C#

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 suc

Solution 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]
publicstaticstringGetGridData()
{
    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);
    }
}

Post a Comment for "'undefined' Reported When Bind Gridview Using Ajax In C#"