Returning multiple objects with a JSON result

Go To


i am wondering if it is possible to return multiple objects with a JSON result in MVC. At the moment i have no problem to return a single object.

public ActionResult AddToBasket(int quantity, int productdetailid) 
    // more code here
    return Json ( new { Name = p.Product.Name, Price = p.Price});

This returns a single anonymous object in my ajax call.What i wanna do is return multiple Names and Prices to fill a table in my view.

So basicly i wanna update(renew) the cookie every time the user adds a item to his basket and update the basket which is a html table.

Thanks in advance.

2012-04-04 20:51
by Wartodust
Have you tried using object[]{ new {...}, new {...} } by any chance - Brad Christie 2012-04-04 20:52
Return a JSON object that contains an array of objects. I can't help you with the specific server side code, however - Anthony Grist 2012-04-04 20:52
what programming language is this - ControlAltDel 2012-04-04 20:52
@user1291492 C - vcsjones 2012-04-04 20:53


Just return some enumerable if you want an array:

return Json ( Enumerable.Range(0, 10).Select(i => new { Name = "N" + i, Price = i });
2012-04-04 20:54
by Alexei Levenkov
But what if the array is dynamic - Wartodust 2012-04-04 21:00
Ok never mind.I understand it now, thanks for your good answer - Wartodust 2012-04-04 21:17


Simply return an array of objects, e.g:

[ { Name: 'foo', Price: 123 }
, { Name: 'bar', Price: 456 }
, { Name: 'baz', Price: 789 } ]
2012-04-04 20:52
by buley
This is JavaScript syntax which is correct but in C# he's asking on the server-side how does he do it which is different than your answer - Jason Sebring 2012-04-04 21:03
Thats correct, and the data is dynamic so i dont know how much objects i need to pass - Wartodust 2012-04-04 21:05