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? Commented 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. Commented Apr 4, 2012 at 20:52
  • what programming language is this? Commented 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 } ]
Sign up to request clarification or add additional context in comments.

2 Comments

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.
Thats correct, and the data is dynamic so i dont know how much objects i need to pass.
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 Comment

But what if the array is dynamic?

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.