8

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.

3
  • Have you tried using object[]{ new {...}, new {...} } by any chance? Apr 4, 2012 at 20:52
  • Return a JSON object that contains an array of objects. I can't help you with the specific server side code, however. Apr 4, 2012 at 20:52
  • what programming language is this? Apr 4, 2012 at 20:52

2 Answers 2

6

Simply return an array of objects, e.g:

[ { Name: 'foo', Price: 123 }
, { Name: 'bar', Price: 456 }
, { Name: 'baz', Price: 789 } ]
2
  • 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. Apr 4, 2012 at 21:03
  • Thats correct, and the data is dynamic so i dont know how much objects i need to pass.
    – nmeuleman
    Apr 4, 2012 at 21:05
5

Just return some enumerable if you want an array:

return Json ( Enumerable.Range(0, 10).Select(i => new { Name = "N" + i, Price = i });
1
  • But what if the array is dynamic?
    – nmeuleman
    Apr 4, 2012 at 21:00

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.