简体   繁体   English

从控制器asp.net返回列表到ajax调用

[英]Return list to ajax call from controller asp.net

I want to return list from my controller to the success function in an AJAX call. 我想通过AJAX调用将列表从控制器返回到成功函数。 I'm able to return the list successfully from controller but inside AJAX call, the code for error gets executed and I get an internal server error. 我能够从控制器成功返回列表,但在AJAX调用中,执行了错误代码,并且收到内部服务器错误。 I searched for the same everywhere, but I'm unable to find a reason why this is happening. 我到处都搜索了相同的内容,但是找不到发生这种情况的原因。

Following is my AJAX: 以下是我的AJAX:

$.ajax({
        type: "POST",
        dataType: 'JSON',
        url: "/BookUtility/GetHallsList",
        success: function (hallsList) {
            console.log(hallsList);
        },
        error: function (xhr,status, exception) {
            console.log("Error: " + exception + ", Status: " + status);
        }
    });

Controller: 控制器:

 Hall objHall = new Hall();
 [HttpPost]
 public JsonResult GetHallsList()
    {
        var hallsList = objHall.GetHallsList();
        return Json(hallsList.ToList());
    }

Hall.cs : Hall.cs

public List<tblHall> GetHallsList()
        {
            List<tblHall> hallsList;
            using (BookingSystemDBEntities db = new BookingSystemDBEntities())
            {
                hallsList = db.tblHalls.ToList();
            }
            return hallsList;
        }

I've also tried using List<tblHall> hallsList = objHall.GetHallsList(); 我也尝试过使用List<tblHall> hallsList = objHall.GetHallsList(); in my controller in place of var hallsList = objHall.GetHallsList(); 在我的控制器中代替var hallsList = objHall.GetHallsList(); , but that doesn't work too. ,但这也不起作用。

This is the error I'm getting: Error I received 这是我得到的错误: 我收到的错误

Where am I going wrong? 我要去哪里错了?

As your error says, the problem is with the web api method. 如您的错误所述,问题出在Web api方法上。 It should throw the error . 它应该抛出错误。 The ObjectContext instance has been disposed and can no longer be used for operations that require a connection. ObjectContext实例已被处置,不能再用于需要连接的操作。 You can fix it by setting 您可以通过设置

using (var contex = new BookingSystemDBEntities())
{
   context.Configuration.LazyLoadingEnabled = false;
   hallsList = db.tblHalls.ToList();
}

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

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