4

I have an MVC controller that returns JSON. I want to read/get that JSON using jQuery and loop through the json items/rows.

Basically I am reading bunch of comments and then show the comments one by one.

Does anyone have code sample to do it?

I get the json correctly. See returned data below.

    $.ajax(
    {
        type: "GET",
        url: "/comment/GetComments",
        dataType: "json",
        data: "blog_id=100&page_size=5&page_no=1",
        success: function (result) {
            //loop the data.. how do I loop json?
        },
        error: function (req, status, error) {
            alert('Error getting comments');
        }
    });

    My controller:

    [HttpGet]
    public ActionResult GetComments(string blog_id, int page_size, int page_no)
    {            
        try
        {                
            List<Comment> comments = ReadCommentsFromDB();

            if(comments .Count > 0)                
                return Json(new { comments = cmts.ToJson() }, JsonRequestBehavior.AllowGet);
            else
                return Json(new { comments = "none" },, JsonRequestBehavior.AllowGet);
        }
        catch (Exception ex)
        {
            return Json(new { comments = ex.ToString() }, JsonRequestBehavior.AllowGet);
        }
    }

Thanks

EDIT:

How do I loop these json returned by controller? I need to loop 3 times and then for each row, I need to have access to all keys and values in that row.

[{ "_id" : { "$oid" : "4dc8" }, "eid" : { "$oid" : "4da" }, "user" : "bob", "text" : "First comment!!", "dt" : { "$date" : 1304966277978 } }, 
 { "_id" : { "$oid" : "4dc8" }, "eid" : { "$oid" : "4da" }, "user" : "bob", "text" : "Second comment!!", "dt" : { "$date" : 1304966347677 } }, 
 { "_id" : { "$oid" : "4dc8" }, "eid" : { "$oid" : "4da" }, "user" : "bob", "text" : "Third comment!!", "dt" : { "$date" : 1304966493240 } }
]
1
  • you did remove [HttpPost] right? Commented May 10, 2011 at 17:32

4 Answers 4

4
success: function(result) {
    $.each(result["comments"], function(key, value) {
        // loop
    });
}

Your result should be a json object

{
    "comments": ...
}

As for the get failing try :

type: "GET",
url: "/comment/GetComments?blog_id=100&page_size=5&page_no=1",
dataType: "json",
//data: "blog_id=100&page_size=5&page_no=1",
Sign up to request clarification or add additional context in comments.

3 Comments

$.each(result["comments"], function(key, value) {} seems an infinite loop. Look at my sample data. Are you sure it will loop the result just 3 times? It keep looping.
@Projapati it's not an infinite loop.
This is my callback. It keep alerting. success: function (result) { $.each(result["comments"], function (key, value) { alert('comment found'); }); }
3
$.ajax(
    {
        type: "GET",
        url: "/comment/GetComments",
        dataType: "json",
        data: "blog_id=100&page_size=5&page_no=1",
        success: function (result) {
            jQuery.each(result['comments'], function(key,val){
               // do stuff :)
            });
        },
        error: function (req, status, error) {
            alert('Error getting comments');
        }
    });

5 Comments

or rather, $.each(result['comments'],function(i,e){ /* e is now an element in the JSON object */ });. Also, not positive, but don't you need to reference result.d?
@Atticus yes I realised it was far too harsh and removed it.
jQuery.each(result['comments'], function(key,val){ // do stuff :) }); might an infinite loop. It is supposed to loop just 3 time as I have 3 top level json objects. Am I missing something?
The loop is infinite. Even if I just return 1 comment, loop never ends!!
How should I know when to stop? I gave 3 as an example. It can be any. $.each() is supposed to loop whatever I have...
2

The answer to your first problem is to allow Json to work in a GET. Json normally only work for a post. You allow Json in GET by using the following return method in your controller (using one of your return statements).

return Json(new { comments = "none" }, JsonRequestBehavior.AllowGet)

Edit: You can also return JsonResult instead of ActionResult as seen below.

public ActionResult GetComments(string blog_id, int page_size, int page_no)    
{           
    try        
    {
        List<Comment> comments = ReadCommentsFromDB();

        // Assuming that Comments will be an empty list if there are no data
        return Json(comments, JsonRequestBehavior.AllowGet)
    }
    catch (Exception ex)
    {
        return Json(new { comments = ex.ToString() }, JsonRequestBehavior.AllowGet));
    }
}

1 Comment

Accepting this. I will ask another question about the looping part.
1

Remove [HttpPost] from your controller method to allow get requests in conjunction with JsonRequestBehavior.AllowGet

What internal server error do you get? what is the message?

1 Comment

Thanks Adam. First problem is solved. But your answer is correct.

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.