title: Return JSON from MVC via AJAX
body: <p>I've been using a hard coded JSON object:</p>
  
  <pre><code>var resuts = [{id: 1, Code: "Code A"}, {id: 2, Code: "Code B"}]
  </code></pre>
  
  <p>I'm then iterating this object calling the items by index and using .length:</p>
  
  <pre><code>for (var i = 0; i &lt; resuts.length; i++) {
              console.log('id:' + resuts[i].id +  ' | ' + 'Code:' + resuts[i].Code}
  </code></pre>
  
  <p>Now I want to pull this data from the server so I created an object to handle the properties and have this action method:</p>
  
  <pre><code>public ActionResult GetResults()
  {
  string json = JsonConvert.SerializeObject(new
          {
              results = new List&lt;Question&gt;()
              {
                  new Question { id = 1, Code = "Code A},
                  new Question { id = 1, Code = "Code B}
              }
          });
  
          return Json(new { data = json }, JsonRequestBehavior.AllowGet);
  }
  </code></pre>
  
  <p>I'm calling it with this AJAX:</p>
  
  <pre><code>function GetResultsJSON() {    
          $.ajax({        
              type: 'GET',        
              url: '/Home/GetResults/',
              dataType: 'json',  
              traditional: true,     
              success: function (data) {            
                  results = data;
              },        
              error: function (data) {
                  alert('Error.');
              }
          })
   };
  </code></pre>
  
  <p>Now my results object contains:</p>
  
  <pre><code>"{" results ":[{" id ":1," Code ":" Code A "},{" id ":1," Code ":" Code B "}]}"
  </code></pre>
  
  <p>Now I get JavaScript errors when trying to use the length property or call items by index.  From what I have read up on, I think my original hard coded object is just an array, however, I have to work differently with the JSON that's returned from my controller.</p>
  
  <p>Can anyone advise on either returning the array format that I was originally working with or the best way to handle the JSON format as it's returned here?  I have tried things like </p>
  
  <pre><code>$.each(data, function(i, obj) {
  alert(obj.name);
  });
  </code></pre>
  
  <p>but this returns undefined.  Any help would be great.</p>