0

I'm trying to get a simple page to pull data from SQL Server via a MVC controller using Json.Net

(Sorry for the dirty code - my day job is a SQL Server Dev\DBA.)

Controller:

dataAdapter.Fill(ds);
DataTable dt = ds.Tables[0];
string strjson = Newtonsoft.Json.JsonConvert.SerializeObject(dt);
return Json(strjson,JsonRequestBehavior.AllowGet);

Index.cshtml:

$.getJSON("/Test/MikeTest", {}, 
 function (myData) {
 alert(myData);
 $.each(myData,function(key,data) {
 alert(key + ":" + data);
 })

returned JSON:

[{"DateTime":"2013-12-02T12:40:57.387","message":"simple test"}] 

When I loop through the JSON data each iteration returns a single character rather than key/name pairs.

Presumably I'm doing something daft & not returning/typing the data correctly - any simple pointers much apprecaited!

asked Dec 2, 2013 at 12:23
4
  • what alert is it showing? Commented Dec 2, 2013 at 12:25
  • 1
    You may prefer using console.loginstead of alert to debug objects. Commented Dec 2, 2013 at 12:30
  • possible duplicate of Loop Through JSON Data Commented Dec 2, 2013 at 12:32
  • I dont know why r u using .each when u r returning single string Commented Dec 2, 2013 at 12:32

1 Answer 1

1

The response from $.getJSON probably is a string, try using "JSON.parse" to make the response an actual object.

Something like:

$.getJSON("/Test/MikeTest", {}, 
 function (myData) {
 alert(myData);
 myDataObj = JSON.parse(myData);
 $.each(myDataObj,function(key,data) {
 alert(key + ":" + data);
 })
 });
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks! that was what I was missing - I ended up with: alert(key + ":" + data.message);

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.