简体   繁体   English

如何将多个列表从控制器动作返回到ajax成功回调函数

[英]how to return the multiple lists from controller action to ajax success call back function

I am creating a mvc .net project in which i have the jquery ajax request is as follows 我正在创建一个mvc .net项目,其中我有jquery ajax请求如下

$.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 call the following 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 send the data in allUser to callback function. 控制器动作将allUser中的数据发送给回调函数。

but what i need is that i want to send both data in alluser and allUser1 to the success function of ajax call 但我需要的是,我想将alluser和allUser1中的数据发送到ajax调用的成功函数

I imagine you want to keep the lists separated. 我想你想要将列表分开。 Wrap them in an object. 将它们包裹在一个物体中。

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

You can access them in your JS like this: 您可以在JS中访问它们,如下所示:

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

You just have to modify your Where clause so you don't need two different lists for the users. 您只需修改Where子句,这样就不需要为用户提供两个不同的列表。 Try this in your getdata method: 在你的getdata方法中试试这个:

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 desired data. allUser现在包含所有需要的数据。

I would create a class that has 2 properties 我会创建一个具有2个属性的类

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 现在您可以将类对象返回给JSON

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM