likestoski
likestoski

Reputation: 1911

JSON results from MVC3 are undefined

I am trying to take the JSON results from an MVC3 action and push it into a table row but the values are all undefined. How can I properly parse the JSON results from a JQuery ajax request?

This is the MVC3 action method

    [HttpPost]
    [Authorize]
    public JsonResult GetImageDetails(int id)
    {
        Image img = db.Images.First(i => i.ID == id);
        return Json(img);
    }

This is the JQuery to handle the results once they return

    $.ajax({
        type: "POST",
        url: "../Controller/GetImageDetails",
        data: "id=" + id,
        dataType: "json",
        success: function (data) {
            $.map(data, function (item) {
                $('#tblImages > tbody > tr:first').before("<tr><td>ID:" + item.ID + "</td><td><img src='" + item.ThumbURL + "' alt='" + item.Name + "'/></td></tr>");
            });
        },
        error: function (obj) {

        }
    })

The result are rows with nothing but undefined. I get the same number of rows as there are properties in the object I'm returning so I'm sure I'm just not handling that JSon result correctly. Can anyone point me in the right direction on how to handle that JSon result please? Also are there any browser support issues with the suggested approach? Thanks in advance!

Upvotes: 1

Views: 1660

Answers (3)

Keith.Abramo
Keith.Abramo

Reputation: 6955

It looks like you are trying to use $.map on a single object. I think this will end up iterating through the property keys of that object. Try just accessing the object properties off the data object

$.ajax({
        type: "POST",
        url: "../Controller/GetImageDetails",
        data: "id=" + id,
        dataType: "json",
        success: function (data) {
                $('#tblImages > tbody > tr:first').before("<tr><td>ID:" + data.ID + "</td><td><img src='" + data.ThumbURL + "' alt='" + data.Name + "'/></td></tr>");
        },
        error: function (obj) {

        }
    })

Upvotes: 1

Ilia G
Ilia G

Reputation: 10211

You are returning a single image from your action, but treating it as an array client-side. Why? Have you tried examining the data and seeing what is actually in it? I am surprised map() call works at all.

Also FYI map() is meant for transforming elements of given array. If you are not returning a value from your callback, then you should be using each() instead.

Upvotes: 0

Jesse
Jesse

Reputation: 8393

Have you tried performing a get on your action vs a post?

eg:

[HttpGet]
[Authorize]
public JsonResult GetImageDetails(int id)
{
    Image img = db.Images.First(i => i.ID == id);
    return Json(img, JsonRequestBehavior.AllowGet);
}

Upvotes: 0

Related Questions