Return Multiple Objects Using ASP.NET MVC'S JsonResult Class

Abstract: The following article demonstrates how to return multiple objects in ASP.NET MVC using the JsonResult class.

Return Multiple Objects Using ASP.NET MVC'S JsonResult Class

I'm always amazed at all the things you can do with ASP.NET MVC with a little thought. I recently had to return multiple objects from an MVC action to a piece of JavaScript code. This was all handled by jQuery's $.getJSON function. Instead of querying the server multiple times for the data, why not return multiple objects from the action to the JavaScript? Sounds easy an it is. This code sample is using the latest jQuery 1.4.2 library and can be downloaded here.

For this article I've got a scenario where I'm using ASP.NET MVC and I want to make an ajax request to an action, and receive multiple JSON objects from the action in one call. This can be accomplished easily by creating an object like the following:

C#

[AcceptVerbs(HttpVerbs.Get)]

publicJsonResult SomeAction()

{

return Json(new {});

}

VB.NET

<AcceptVerbs(HttpVerbs.Get)> _

PublicFunction SomeAction() As JsonResult

Return Json(NewWith {})

EndFunction

The return object for this example will be an anonymous object. For this example, I'm going to return an object that lists the months in a year, and also another object which displays the environment variables from your computer. Now I want these two objects returned when I make one ajax call through JavaScript. Here's the server code below. First off I'm going to create a class that holds a Text/Value object:

In the code above, I'm returning JSON that contains two objects, EnvironmentVariables and MonthsInYear. To return two objects, the action's result is Json, but I'm using new {} to return an anonymous object:

C#

return Json(new {});

I simply create new objects by supplying a name and a value for the object:

Malcolm Sheridan is a Microsoft awarded MVP in ASP.NET, a Telerik Insider and a regular presenter at conferences and user groups throughout Australia and New Zealand. Being an ASP.NET guy, his focus is on web technologies and has been for the past 10 years. He loves working with ASP.NET MVC these days and also loves getting his hands dirty with jQuery and JavaScript. He also writes technical articles on ASP.NET for SitePoint and other various websites. Follow him on twitter @malcolmsheridan

Feedback - Leave us some adulation, criticism and everything in between!