Note that there are some explanatory texts on larger screens.

plurals
  1. POIterating over Json collection using JQuery iterates over chars of the data string
    primarykey
    data
    text
    <p>I am using ASP.MVC 1 to return an IEnumerable of objects (say, Cars):</p> <pre><code>public class Car : Entity&lt;Car&gt; { public virtual string Make { get; set; } public virtual double Length { get; set; } public virtual string Colour { get; set; } } </code></pre> <p>like this:</p> <pre><code>[AcceptVerbs(HttpVerbs.Post)] public JsonResult GetRoutes() { IEnumerable&lt;Car&gt; cars = _carTask.GetCars(); return Json(cars); } </code></pre> <p>In my page, I want to iterate over each car returned, so I have this:</p> <pre><code>$.post("/Home/GetCars", null, function(cars) { alert("type of object returned is " + typeof cars + ", content is " + cars); $.each(routes, function() { alert(this); }); } ); </code></pre> <p>When I run this, the first alert box says: </p> <p>type of object is string, content is [{"Make":"BMW"}, {"Make":"Ford"}]</p> <p>Which tells me I am getting a string back (shouldn't i get an object back?), containing a Json structure with 2 objects. However the jquery $.each function then proceeds to iterate over each char in the string, so I get 46 alert boxes: the first says '[', then '{', then '"', then 'M', then 'a', then 'k'... you get the idea.</p> <p>From what I have read, jQuery should be parsing this as a collection, and should iterate only twice to show me to alerts, one for each car. I could then do alert(car.Make) to display the makes, but if I try that I get undefined (because a string doesnt have a Make property).</p> <p>What am I doing wrong? Thanks for any help, there must be an obvious error but i promise I have done plenty of googling first and came up with nothing! :)</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload