I'm designing a page which makes an ajax call (via jQuery.ajax) to a page method on the server side.
On the server side, I have two classes: Agent
and Channel
.
In the page method, I'd like to return a List<Agent>
and a List<Channel>
to the client side.
How can I return two lists to client side? should wrap them up in one class like:
public class ReturnData
{
public List<Agent> Agents{ get; set; }
public List<Channel> Channels{ get; set; }
}
Or is there a better way?
Also, How can I access to these lists' items in client side? Something like foreach(var item in Agents)
but in client side?
Controller code
public ActionResult SomeAction()
{
List<Agent> collectionOfAgents = //get your collection
List<Channels> collectionOfChannels = //get your collection
var jsonData = new
{
Agents =collectionOfAgents,
Channels = collectionOfChannels
};
return Json(jsonData);
}
Jquery code
jQuery.ajax({
url: '/Controller/SomeAction',
type: "POST",
dataType: "json",
success: function (data) {
var collectionOfAgents = data.Agents;
//iterate over agents
for(var a in collectionOfAgents)
{
alert(collectionOfAgents[a]);
}
var collectionOfChannels = data.Channels;
//iterate over channels
for(var c in collectionOfChannels)
{
alert(collectionOfChannels[c]);
}
}
});