0

I want to access json data into jQuery returning from Asp.Net Web Method. This is my web Method

[WebMethod(EnableSession=true)]
public string GetChat() {
    //
    // Code to get data into dataset from database
    //

    // below code to convert dataset to json string
    JavaScriptSerializer serializer = new JavaScriptSerializer();
    List<Dictionary<string, object>> rows = new List<Dictionary<string, object>>();
    Dictionary<string, object> row;

    foreach (DataRow dr in ds.Tables[0].Rows)
    {
        row = new Dictionary<string, object>();
        foreach (DataColumn dc in ds.Tables[0].Columns)
        {
            row.Add(dc.ColumnName.Trim(), dr[dc]);
        }
        rows.Add(row);
    }

    return serializer.Serialize(rows);
}

Here is my jQuery Code.

$.ajax({
    type: "POST",
    contentType: "application/json",
    url: "../chat.asmx/GetChat",
    dataType: "json",
    success: function (data) {
        alert(data.d[0].Name);
    },
    error: function (result) {
        alert("Error");
    }
});

Here is Json Response Sample:

[
{
    "EmployeeId":3,
    "Name":"Khushbu Agarwal",
    "Cnt":2
},
{
    "EmployeeId":6,
    "Name":"Priyanka Jain",
    "Cnt":3
}
]

Now, When I access data in jQuery by statement:

alert(data.d[0].Name);

It displays Undefined Can any one help me on this. I am new to json. Thanks in advance.

2
  • When you run in debug, are you hitting the method? Also, use console.log and not alert, you'll get some better information using the chrome/firebug tools Commented Nov 30, 2013 at 9:41
  • Console.log method also display undefined. and I am already using and tracing Javascript and AJAX by Firebug Console. Commented Nov 30, 2013 at 10:26

1 Answer 1

1

You have double JSON serialization here. Don't do plumbing in your WebMethod. Just return an object that will hold the data:

[WebMethod(EnableSession=true)]
public List<Dictionary<string, object>> GetChat() 
{
    List<Dictionary<string, object>> rows = new List<Dictionary<string, object>>();

    foreach (DataRow dr in ds.Tables[0].Rows)
    {
        Dictionary<string, object> row = new Dictionary<string, object>();
        foreach (DataColumn dc in ds.Tables[0].Columns)
        {
            row.Add(dc.ColumnName.Trim(), dr[dc]);
        }
        rows.Add(row);
    }

    return rows;
}

and then inside your success callback for example if you wanted to access the first row:

success: function (data) {
    alert(data.d[0]);
},

And if you wanted to access some particular columns name of the first row:

alert(data.d[0]['ColumnName'].Value);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.