How do I return JSON and loop through the returned json in jQuery in MVC app?

前端 未结 4 848
情书的邮戳
情书的邮戳 2021-01-06 09:13

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

相关标签:
4条回答
  • 2021-01-06 09:45

    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));
        }
    }
    
    0 讨论(0)
  • 2021-01-06 09:48
    $.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');
            }
        });
    
    0 讨论(0)
  • 2021-01-06 09:59
    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",
    
    0 讨论(0)
  • 2021-01-06 10:07

    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?

    0 讨论(0)
提交回复
热议问题