views:

1688

answers:

3

I am using ASP.MVC 1 to return an IEnumerable of objects (say, Cars):

public class Car : Entity<Car>
{
    public virtual string Make { get; set; }
    public virtual double Length { get; set; }
    public virtual string Colour { get; set; }
}

like this:

[AcceptVerbs(HttpVerbs.Post)]
public JsonResult GetRoutes()
{
    IEnumerable<Car> cars = _carTask.GetCars();
    return Json(cars);
}

In my page, I want to iterate over each car returned, so I have this:

$.post("/Home/GetCars", null, 
    function(cars)
    {
         alert("type of object returned is " + typeof cars + ", content is " + cars);
         $.each(routes, function()
         {
              alert(this);
         });
    }
);

When I run this, the first alert box says:

type of object is string, content is [{"Make":"BMW"}, {"Make":"Ford"}]

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.

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).

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! :)

+3  A: 

Try adding the type "json" as the last parameter in your $.post() method. Also, I think you can simplify your each statement:

$.post("/Home/GetCars", null, 
    function(cars)
    {
         $(cars).each(function() {
             alert(this); //this should point to the car. 
         });
    },
   "json"
);
Nick Riggs
Thanks, this did the trick!
James Allen
+1  A: 

You forgot to tell jquery to interpret the results as json. By default $.post just returns a string of the data. You can use one of the following options. Then when you iterate they'll be objects.

http://docs.jquery.com/Ajax/jQuery.getJSON

Or add "json" as the last parameter to post

Sean Clark Hess
You got the same answer as Nick but he got there first so I marked his as the answer :( Thanks for your reply!
James Allen
A: 

link text

$.post("/Home/GetCars", null, 
    function(cars)
    {
         $.each(cars, function() {
              alert(this.Make);
         });
    },
   "json"
);
andres descalzo
Thanks I was missing the "json" (Tried once, didn't work, then I re-read the replies and realised I had it in the wrong place, after the $.each call)
James Allen