1

So I have a function in my code, that I'm calling using jQuery's getJSON. Here's the function:

public JsonResult GetItems()
{
    var items = (from x in GetAllItems()
                 select new { x.ItemID, x.ItemType.Name, x.Description })
                .ToList();


    JsonResult result = Json(items, JsonRequestBehavior.AllowGet);

    return Json(result, JsonRequestBehavior.AllowGet);
}

And this is where I'm calling it with jQuery:

$.getJSON('/MyController/GetItems/', function (data) {
    // somehow iterate through items, displaying ItemID, Name, and Description
});

But I'm stuck here, I'm not sure what to do. I'd like to iterate through each item, and display the ItemID, Name, and Description in an alert box. But every example I've found just shows how iterate and display items that only have a key and a value, but my items have move than 2 properties to display.

2 Answers 2

3

Try this:

$.getJSON('/MyController/GetItems/', function (data) {
    var name, itemId, description;
    $.each(data, function(){
         name = this.Name;
         itemId = this.ItemID;
         description = this.Description ;
         //You can use these variables and display them as per the need.  
    });
});
Sign up to request clarification or add additional context in comments.

Comments

1

Use firebug to debug your javascript code. There you can see what result you have in your data object if you set a breakpoint in your code. My guess is that should write something like:

$.getJSON('/MyController/GetItems/', function (data) {
    for(var i = 0; i < data.length; i++) { // add a breakpoint here 
                                           // to see if reach the line and 
                                           // the content of data
        // do your funky stuff here
    }
});

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.