我是新手,在MVC ASP.net中使用datatables和ajax。我有问题,我很难解决这个问题。我尝试连接两个表,如标题所示,并将结果返回到json并显示到datatable。但我得到&#34的错误;由于已经处理了DbContext,因此无法完成操作。"。任何帮助都对我学习这门语言很有帮助。谢谢
这是我的代码
public ActionResult Rooms()
{
using (RoomReservationEntities db = new RoomReservationEntities())
{
var room_query = from room in db.Rooms
join roomType in db.Room_Type
on room.RoomType_id equals roomType.RoomType_id
select new { room.Room_id, room.Room_name, roomType.RoomType, roomType.Room_rate };
return Json(new { data = room_query }, JsonRequestBehavior.AllowGet);
}
}
我的cshtml
@{
ViewBag.Title = "Rooms";
Layout = "~/Views/Shared/_AdminMasterPage.cshtml";
}
<h2>Rooms</h2>
<link rel="stylesheet" href="https://cdn.datatables.net/1.10.13/css/jquery.dataTables.min.css" />
<h2>AdminRooms</h2>
<div style="width:90%; margin:0 auto">
<table id="myDatatable">
<thead>
<tr>
<th>Room Name</th>
<th>Room Type</th>
<th>Room Rate</th>
</tr>
</thead>
</table>
</div>
@section scritps{
<script src="~/Scripts/jquery.validate.min.js"></script>
<script src="~/Scripts/jquery.validate.unobtrusive.min.js"></script>
<script src="https://cdn.datatables.net/1.10.13/js/jquery.dataTables.min.js"></script>
<script src="~/Scripts/jquery-ui-1.12.1.min.js"></script>
}
<script>
$(document).ready(function () {
var oTable = $('#myDatatable').DataTable({
"ajax": {
"url": '/Admin/Rooms',
"type": "get",
"datatype":"json"
},
"columns": [
{ "data": "Room_name", "autoWidth": true },
{ "data": "RoomType", "autoWidth": true },
{ "data": "Room_rate", "autoWidth": true }
]
})
})
</script>
答案 0 :(得分:3)
这是因为你正在使用“使用”阻止使用块调用Dispose方法一找到结束括号。 另一个原因可能是因为Linq查询在ToList()或枚举访问之前不会触发。在您的代码中,没有这样的方法可以检查以下代码:
public ActionResult Rooms()
{
using (RoomReservationEntities db = new RoomReservationEntities())
{
var room_query = (from room in db.Rooms
join roomType in db.Room_Type
on room.RoomType_id equals roomType.RoomType_id
select new { room.Room_id, room.Room_name, roomType.RoomType, roomType.Room_rate }).ToList();
return Json(new { data = room_query }, JsonRequestBehavior.AllowGet);
}
}
您可以找到有关Linq查询早期绑定和后期绑定的更多信息