How to return multiple lists from controller action to ajax callback function

I am creating an mvc.net project in which I have a jquery ajax request as follows

$.ajax({ url: "@Url.Action("getdata", "SeatPlans")", data: { seat_plane_id : 17}, type: "POST", dataType: "json", success: function (data) { loadData(data); }, error: function () { alert("Failed! Please try again."); } }); 

which trigger the next controller action

 public JsonResult getdata(int seat_plane_id) { int lid = seat_plane_id; List<SeatPlans> allUser = new List<SeatPlans>(); allUser = db.SEATPLAN.Where(d => d.layout_id == lid).ToList(); lid++; List<SeatPlans> allUser1 = new List<SeatPlans>(); allUser1 = db.SEATPLAN.Where(d => d.layout_id == lid).ToList(); return new JsonResult { Data = allUser,JsonRequestBehavior = JsonRequestBehavior.AllowGet }; } 

the code is working fine. the controller action sends data to allUser for the callback function.

but I need me to want to send both data to alluser and allUser1 to the success function of the ajax call

+7
javascript c # ajax asp.net-mvc-4
source share
3 answers

I would create a class that has 2 properties

 int lid = seat_plane_id; List<List<SeatPlans>> listOfSeatPlans (a collection of collections) List<List<SeatPlans>> list = new ... list.Add(allUser); list.Add(someUsers); 

Now you can return the class object back to JSON

+1
source share

I assume you want the lists to be split. Wrap them in an object.

 var data = new { allUser = allUser , allUser1 = allUser1 }; return Json(yourObject, JsonRequestBehavior.AllowGet); 

You can access them in your JS as follows:

 success: function (data) { var allUser = data[0]; var allUser1 = data[1]; //use the data as you see fit. loadData(allUser); loadData(allUser1 ); }, 
+5
source share

You just need to change the Where clause so you don't need two different lists for users. Try this in the getdata method:

 public JsonResult getdata(int seat_plane_id) { int lid = seat_plane_id; List<SeatPlans> allUser = new List<SeatPlans>(); allUser = db.SEATPLAN.Where(d => d.layout_id == lid || d.layout_id == (lid+1)).ToList(); return new JsonResult { Data = allUser,JsonRequestBehavior = JsonRequestBehavior.AllowGet }; } 

allUser now includes all the data you need.

+3
source share

All Articles