rails - Error Ajax-jquery datatable
jquery deferred exception $(.datatable is not a (2)
Estoy usando jquery datatable en mi aplicación.
Cuando intento vincular la respuesta json del servidor, recibo el siguiente mensaje en el navegador
DataTables warning:table id=DataTables_Table_0-Ajax error.For more information about this error please seee http://datatables.net/tn/7
y en la consola del navegador como
Failed to load resource: the server responded with a status of 500 (Internal Server Error)
.
Cuando buceé más profundamente en la consola obtuve la siguiente excepción. A circular reference was detected while serializing an object of type ''System.Data.Entity.DynamicProxies.CenterCode_16F8807C95C21FEFA99B4700E38D8ACB4A88C8E560B5640BD5E1FA148C99CCA5''.
Y no sé lo que esto significa?
Josn regresa exitosamente sin ningún error? ¿Cómo puedo resolver este problema?
Función JsonResult
public JsonResult GetDataTable(string finYear)
{
try
{
Common _cmn = new Common();
List<RegistraionVM.RegDataTable> _dTableReg = new List<RegistraionVM.RegDataTable>();
_dTableReg = _db.StudentRegistrations
.AsEnumerable()
.Where(r => _centerCodeIds.Contains(r.StudentWalkInn.CenterCode.Id)
&& (r.TransactionDate.Value.Date >= _startFinDate && r.TransactionDate.Value.Date <= _endFinDate))
.Select(r => new RegistraionVM.RegDataTable
{
Centre = r.StudentWalkInn.CenterCode.CentreCode,
CourseFee = r.TotalCourseFee.Value,
Discount = r.Discount.Value,
CurrEmpId = Int32.Parse(Session["LoggedUserId"].ToString()),
WalkInn = r.StudentWalkInn,
Receipt = r.StudentReceipts.Where(rc => rc.Status == false).FirstOrDefault(),
RegDate = r.TransactionDate,
RegistrationID = r.Id,
SalesPerson = r.StudentWalkInn.CROCount == (int)EnumClass.CROCount.ONE ?
r.StudentWalkInn.Employee1.Name :
r.StudentWalkInn.Employee1.Name + "," + r.StudentWalkInn.Employee2.Name,
StudentName = r.StudentWalkInn.CandidateName,
SoftwareUsed = string.Join(",", r.StudentRegistrationCourses
.SelectMany(c => c.MultiCourse.MultiCourseDetails
.Select(mc => mc.Course.Name))),
IsSalesIndividual = _currentRole == (int)EnumClass.Role.SALESINDIVIDUAL ? true : false
}).OrderByDescending(r => r.RegistrationID).ToList();
return Json(new { data = _dTableReg }, JsonRequestBehavior.AllowGet);
}
catch (Exception ex)
{
return Json(new { data = "" }, JsonRequestBehavior.AllowGet);
}
}
RegDataTable
public class RegDataTable
{
public int RegistrationID { get; set; }
public DateTime? RegDate { get; set; }
public string Centre { get; set; }
public string SalesPerson { get; set; }
public string StudentName { get; set; }
public int Discount { get; set; }
public int CourseFee { get; set; }
public string SoftwareUsed { get; set; }
public StudentReceipt Receipt { get; set; }
public bool IsSalesIndividual { get; set; }
public StudentWalkInn WalkInn { get; set; }
public int CurrEmpId { get; set; }
public int? NextDueAmount
{
get { return Receipt == null ? 0 : Receipt.Total; }
}
public string NextDueDate
{
get { return Receipt == null ? "" : Receipt.DueDate.Value.ToString("dd/MM/yyyy"); }
}
public string MobileNo
{
get
{
if (IsSalesIndividual)
{
if ((CurrEmpId == WalkInn.CRO1ID) || (CurrEmpId == WalkInn.CRO2ID))
{
return WalkInn.MobileNo;
}
else
{
return "-";
}
}
else
{
return WalkInn.MobileNo;
}
}
}
}
html
<table class="table table-bordered table-striped dTable" data-url="@Url.Action("GetDataTable", "Registration")">
<thead>
<tr>
<th>RegDate</th>
<th>Centre </th>
<th>Sales Person </th>
<th>Student Name</th>
<th>Mobile</th>
<th style="width:200px">S/W Used</th>
<th>Discount</th>
<th>CourseFee</th>
<th>Next DueDetails</th>
<th style="display:none">NextDueAmount</th>
<th ></th>
</tr>
</thead>
</table>
Llamar a DataTable desde javascript
table = $(".dTable").dataTable({
...
...,
columns: [
{ "data": "RegDate" },
{ "data": "Centre" },
{ "data": "SalesPerson" },
{ "data": "StudentName" },
{ "data": "MobileNo" },
{ "data": "SoftwareUsed" },
{ "data": "Discount" },
{ "data": "CourseFee" },
{ "data": "NextDueDate" },
{ "data": "NextDueAmount" },
{ "data": "RegistrationID" }
],
//Defining checkbox in columns
"aoColumnDefs": [
{
"targets": [0],
"render": function (data, type, full, meta) {
var date = new Date(parseInt(data.substr(6)));
var month = date.getMonth() + 1;
return date.getDate() + ''/'' + month + ''/'' + date.getFullYear()
}
},
{
"targets": [8],
"bSortable": false,
"render": function (data, type, row) {
if (row.NextDueAmount != 0) {
return data + '','' + row.NextDueAmount
}
else {
return "FULL PAID"
}
}
},
],
});
Deberías devolver Json (resultado). Después de haber creado la lista, solo está devolviendo datos vacíos si se lanza una excepción. Cambia el resultado de tu método a:
return Json(result);
}
catch (Exception ex)
{
return Json(new { error = ex.Message });
}
}
Usted * DEBE agregar una etiqueta <tbody>
en blanco en su tabla, como;
<table>
<thead>...</thead>
<tbody></tbody>
</table>
Para que los scripts de dataTable puedan agregar datos a tbody e inicializar la tabla.