0

I know this question may have been asked hundreds of times and that there is tons of examples about and probably I may be downvoted, but I have to ask it any way because I don't know in what side (controller, script or both) my code is incorrect and also b/c I couldn't find an example on how to cast an object into a two-dimensional array (which is what I believe the result is): I need to pass a List> from the MVC controller back to the ajax script, then manipulate the array results, but I don't know how to cast the array to read its elements.

[HttpGet]
public ActionResult ListBoxCustomize(string listName)
   {
      var result = new List<KeyValuePair<string, string>>();  // Key , Value

      // Code to add items to the list 
      .........

      return Json(new { items = result }, JsonRequestBehavior.AllowGet);
}

JScript

$.ajax(
{
    success: function (data) // THIS IS WHAT IS RETURNED -> data = Object {items: Array[5]}
    {
    alert( items[0][0] ) // Reference Error: items is not defined 
    OR
    alert( data[0][0] ) // Uncaught TypeError: Cannot read property "0" of undefined         

    .... and so it goes with all other cast and combinations that I've tried.          

    }   
1
  • 1
    Did you mean to call data.items[0][0] instead of items[0][0]? Commented Feb 9, 2016 at 21:29

1 Answer 1

1

In your javascript, your parameter is named data but your alert is passed items. What happens if you do alert(items[0][0])? Or break into the debugger in your browser's dev tools and look at the object structure? Another option would be to use a tool like Fiddler to look at the actual response being returned; once you see the data on the wire it's usually pretty straightforward to process it on the client.

Sign up to request clarification or add additional context in comments.

3 Comments

This is what comes back from the controller: data = Object {items: Array[5]} How can I read that?
Well, data, is an object with one field named items which is an array of five items. What happens if you do alert(data.items[0])?
That worked! just needed to add the name like data.items[0].Key

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.