Reputation: 39
I'm getting the "The ObjectContext instance has been disposed and can no longer be used for operations that require a connection" error message on my intranet app when I try to implement a jQuery DataTable for a relational SQL database.
This is my HomeController code:
using CyberAssets.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace CyberAssets.Controllers
{
public class HomeController : Controller
{
public ActionResult Index()
{
return View();
}
public ActionResult loaddata()
{
using (CyberAssetsEntities dc = new CyberAssetsEntities())
{
var data = dc.CyberAssets.OrderBy(a => a.Id).ToList();
return Json(new { data = data }, JsonRequestBehavior.AllowGet);
}
}
}
}
This is the code for my View with the DataTable:
@section Scripts {
<script src="//cdn.datatables.net/1.10.15/js/jquery.dataTables.min.js"></script>
<script>
$(document).ready(function () {
$('#DataTbl').DataTable({
"ajax": {
"url": "/Home/loaddata",
"type": "GET",
"datatype": "json"
},
"columns": [
{ "data": "FacilityName", "autowidth": true },
{ "data": "FacilityType", "autowidth": true },
{ "data": "MachineType", "autowidth": true },
{ "data": "MachineFunctionDesc", "autowidth": true },
{ "data": "PhysicalLocation", "autowidth": true }
]
});
});
</script>
}
How can I preload the objects that I need to refer to within the loaddata()
using
block in my HomeController and basically "avoid" lazy-loading?
Upvotes: 1
Views: 1428
Reputation: 1251
You need to add following lines to your DataTable initialization code:
"processing": true,
"serverSide": true,
So you code for DataTable should look like this:
$('#DataTbl').DataTable({
"processing": true,
"serverSide": true,
"ajax": {
"url": "/Home/loaddata",
"type": "GET",
"datatype": "json"
},
"columns": [
{ "data": "FacilityName", "autowidth": true },
{ "data": "FacilityType", "autowidth": true },
{ "data": "MachineType", "autowidth": true },
{ "data": "MachineFunctionDesc", "autowidth": true },
{ "data": "PhysicalLocation", "autowidth": true }
]
});
Upvotes: 1