I have two datatables, one which lists foldes, and another which list's files within their parent folder. Here is how my script looks for the folder table:
var oTable = $('#folderTable').dataTable({
"bServerSide": true,
"sAjaxSource": "AJAXViewFolders",
"bProcessing": true,
"bFilter": false,
"aoColumns": [
{ "sName": "folder_id",
"bSearchable": false,
"bSortable": false,
"fnRender": function (oObj) {
return 'View';
}
},
{ "sName": "folder_name" },
{ "sName": "create_date" }
]
});
});
Now, when the user clicks the link I need to be able to pass that parentid to the file datatable. I have had no luck thus far. Here is how the JSON result looks in my controller, for the files datatable:
public JsonResult AJAXViewFiles(DataTableParamModel dtParams, int parentid)
{
var repo = new TrusteeDocumentRepository();
var allDocuments = repo.FindAllFiles().Where(c=>c.folder_id == parentid);
IEnumerable<Files> filteredFiles;
filteredFiles = allDocuments;
var displayedFiles = filteredFiles.Skip(dtParams.iDisplayStart).Take(dtParams.iDisplayLength);
var result = from c in displayedFiles select new[] { Convert.ToString(c.folder_id),c.file_name, c.upload_date.ToString() };
return Json(new
{
sEcho = dtParams.sEcho,
iTotalRecords = allDocuments.Count(),
iTotalDisplayRecords = filteredFiles.Count(),
aaData = result
},
JsonRequestBehavior.AllowGet);
}
How would I go about getting the link in the folder table to pass the parentid to the jsonresult for the file's datatable successfully?
I assume the dataTables are on the same page so I'd switch it to a button...
"fnRender": function (oObj) {
return '<button type="button" class="folder-view" data-id="' + oObj.aData[0] + '">View</button>';
}
Add a live click handler so you can set the current parentid and refresh the files dataTable. Handler might look like this...
$('.folder-view').on('click', function() {
var $filesTable = $('#filesTable');
$filesTable.attr('data-parentid', $(this).attr('data-id'));
//refresh the files table
$filesTable.dataTable().fnDraw(false);
});
Finally, the files dataTable will need to override the fnServerData function to merge the extra parentid data...
"fnServerData": function (sSource, aoData, fnCallback) {
var extraData = [ { parentid: $('#filesTable').attr('data-parentid') } ];
$.ajax({
"dataType": "json",
"type": "POST",
"url": sSource,
"data": $.merge(extraData, aoData),
"success": fnCallback
});
}
Related
I have used jquery datatable Server-side processing in my application (asp web form ), after the data returned, paging, searching and sorting do not work. I've read several cases here on the forum of similar or equal problems, but I still haven't been able to solve mine. Could you look at my code, please?
datatable
<script type="text/javascript">
$(document).ready(function () {
$("#stockDatatable").DataTable({
"processing": true, //show processing message
"serverSide": true, //is server side
"filter": true, //allow filter
"ajax": {
"url": "WebForm2.aspx/GetData", //endpoint to get data
"contentType": "application/json",
"type": "GET",
"dataType": "JSON",
"data": function (d) {
return d;
},
"dataSrc": function (json) {
json.draw = json.d.draw;
json.recordsTotal = json.d.recordsTotal;
json.recordsFiltered = json.d.recordsFiltered;
json.data = json.d.data;
var return_data = json.d.data;
return return_data;
}
},
"columns": [ // columns to populate
{ "data": "Id" },
{ "data": "Code"},
{ "data": "Type" },
{ "data": "Text_Description" },
{ "data": "Date_Time" },
{ "data": "Date_Created"},
{ "data": "Added_by" },
],
});
});
</script>
Code Behind (Webform2.cs)
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json, UseHttpGet = true)]
public static object GetData()
{
DataTables result = new DataTables();
using (var db = new MunchData())
{
string search = HttpContext.Current.Request.Params["search[value]"];
string draw = HttpContext.Current.Request.Params["draw"];
string order = HttpContext.Current.Request.Params["order[0][column]"];
string sortColumnDirection = HttpContext.Current.Request.Params["order[0][dir]"];
int startRec = Convert.ToInt32(HttpContext.Current.Request.Params["start"]);
int pageSize = Convert.ToInt32(HttpContext.Current.Request.Params["length"]);
string start = HttpContext.Current.Request.Params["start"];
int skip = start != null ? Convert.ToInt32(start) : 0;
var data = db.Machineinfoes.OrderByDescending(p => p.Id).ToList();
int totalRecords = data.Count;
int recFilter = data.Count;
result.draw = Convert.ToInt32(draw);
result.recordsTotal = totalRecords;
result.recordsFiltered = recFilter;
result.data = data.Skip(skip).Take(pageSize).ToList();
}
return result;
}
The problems is Datatables JS stays in state "processing" and the Chrome debug throws:
Uncaught TypeError: Cannot read property 'length' of undefined
The code in question that "feeds" datatables js is (data is some linq query):
var jsonData = Json(data);
return jsonData;
The response is (textual response):
[{
"TotalCredito": 1649112940.000000,
"TotalClientes": 1040,
"Balance7": 188974066.000000,
"Balance37": 25152742.000000,
"Balance67": 53268069.000000,
"Mes": 1
}, {
"TotalCredito": 1910576150.000000,
"TotalClientes": 941,
"Balance7": 332301396.000000,
"Balance37": 84407873.000000,
"Balance67": -7053061.000000,
"Mes": 2
}, {
"TotalCredito": 1852843443.000000,
"TotalClientes": 809,
"Balance7": 300589569.000000,
"Balance37": 87170595.000000,
"Balance67": 41900708.000000,
"Mes": 3
}, {
"TotalCredito": 1736522626.000000,
"TotalClientes": 747,
"Balance7": 235758479.000000,
"Balance37": 107699635.000000,
"Balance67": 60831390.000000,
"Mes": 4
}, {
"TotalCredito": 1611546395.000000,
"TotalClientes": 702,
"Balance7": 201209547.000000,
"Balance37": 59028449.000000,
"Balance67": 64171607.000000,
"Mes": 5
}, {
"TotalCredito": 1306131513.000000,
"TotalClientes": 697,
"Balance7": 552835099.000000,
"Balance37": 67349028.000000,
"Balance67": 50490441.000000,
"Mes": 6
}]
And the script function in the view is:
<script>
$(document).ready(function () {
var datatable = $('#informe').dataTable({
"language": { "url": "http://cdn.datatables.net/plug-ins/28e7751dbec/i18n/Spanish.json" },
"bFilter": false,
"processing": true,
"serverSide": true,
"ajax": {
"url": "somesupercoolurl",
"type": "POST",
"dataType": "json"
},
"columns": [
{ "data": "Balance7" },
{ "data": "Balance37" },
{ "data": "Balance67" },
{ "data": "Mes" },
{ "data": "TotalClientes" },
{ "data": "TotalCredito" }
],
});
});
Finally, the table is:
<table id="informe">
<thead>
<tr>
<th>Balance7</th>
<th>Balance37</th>
<th>Balance67</th>
<th>Mes</th>
<th>TotalClientes</th>
<th>TotalCredito</th>
</tr>
</thead>
</table>
I find it strange that while the information is properly formatted, is not able to process.
Finally, i resolve this
after seeing many examples, I noticed it's necessary include this 3 variables to json before parse the json object to datatables js; In the controller:
var totalDatos = data.Count();
var jsonData = Json(new {
iTotalDisplayRecords = totalDatos,
iTotalRecords = totalDatos,
aaData = data
});
return jsonData;
Whit this 'function', the json object is like this
{"iTotalDisplayRecords":6,"iTotalRecords":6,"aaData":[{"TotalCredito":1649112940.000000,"TotalClientes":1040,"Balance7":188974066.000000,"Balance37":25152742.000000,"Balance67":53268069.000000,"Mes":1},{"TotalCredito":1910576150.000000,"TotalClientes":941,"Balance7":332301396.000000,"Balance37":84407873.000000,"Balance67":-7053061.000000,"Mes":2},{"TotalCredito":1852843443.000000,"TotalClientes":809,"Balance7":300589569.000000,"Balance37":87170595.000000,"Balance67":41900708.000000,"Mes":3},{"TotalCredito":1736522626.000000,"TotalClientes":747,"Balance7":235758479.000000,"Balance37":107699635.000000,"Balance67":60831390.000000,"Mes":4},{"TotalCredito":1611546395.000000,"TotalClientes":702,"Balance7":201209547.000000,"Balance37":59028449.000000,"Balance67":64171607.000000,"Mes":5},{"TotalCredito":1306131513.000000,"TotalClientes":697,"Balance7":552835099.000000,"Balance37":67349028.000000,"Balance67":50490441.000000,"Mes":6}]}
The table, in the view:
<table id="informe">
<thead>
<tr>
<th>Mes</th>
<th>TotalCredito</th>
<th>TotalClientes</th>
<th>Balance7</th>
<th>Balance37</th>
<th>Balance67</th>
</tr>
</thead>
</table>
The Script is:
<script>
$(document).ready(function () {
var arrayDatos = {
'canal': $(" #ListaCanales ").val(),
'anio': $(" #ListaAnios ").val(),
'vendedorsigla': $(" #ListaVendedores ").val()
};
var datatable = $('#informe').dataTable({
"language": { "url": "http://cdn.datatables.net/plug-ins/28e7751dbec/i18n/Spanish.json" },
"bFilter": false,
"processing": true,
"serverSide": true,
"ajax": {
"url": "mensualajax",
"type": "POST",
"dataType": "json",
"data": arrayDatos
},
"columns": [
{ "data": "Mes", "bSortable": false },
{ "data": "TotalCredito" },
{ "data": "TotalClientes" },
{ "data": "Balance7" },
{ "data": "Balance37" },
{ "data": "Balance67" }
],
});
$(" #FiltrarResultados ").click(function () {
var arrayDatos = {
'canal': $(" #ListaCanales ").val(),
'anio': $(" #ListaAnios ").val(),
'vendedorsigla': $(" #ListaVendedores ").val()
};
datatable.fnClearTable();
$('#informe').dataTable({
"bDestroy": true,
"language": { "url": "http://cdn.datatables.net/plug-ins/28e7751dbec/i18n/Spanish.json" },
"bFilter": false,
"processing": true,
"serverSide": true,
"ajax": {
"url": "mensualajax",
"type": "POST",
"dataType": "json",
"data": arrayDatos
},
"columns": [
{ "data": "Mes", "bSortable": false },
{ "data": "TotalCredito" },
{ "data": "TotalClientes" },
{ "data": "Balance7" },
{ "data": "Balance37" },
{ "data": "Balance67" }
],
});
});
});
is important remark, i use the 'click' function to reload whit ajax the datatables, the 'click' function is nearly equal to the another, but i aggregate "bDestroy": true,in the datatable constructor to reload the datatables (It is not very elegant, but work).
Finally, my new superduper controller to render, capture and updating data with DatatablesJs
//repository with the query
var repositorio = new Repositorios.InformeMensualController();
//capture ajax
string canal = String.Join("", Request.Form.GetValues("canal"));
string auxAnio = String.Join("", Request.Form.GetValues("anio"));
int anio = Convert.ToInt32(auxAnio);
string auxVendedorCodigo = String.Join("", Request.Form.GetValues("vendedorsigla"));
int vendedorCodigo = Convert.ToInt32(auxVendedorCodigo);
//set up data
var data = repositorio.CargaDatos(canal, anio, vendedorCodigo);
//Transformación a JSON y Datatables JS.
var totalDatos = data.Count();
var jsonData = Json(new {
iTotalDisplayRecords = totalDatos,
iTotalRecords = totalDatos,
aaData = data});
return jsonData;
I hope this is useful to someone
regards! :)
I am trying to get the pagination to work but it's not working. I have over 90k records in the database but it only displays 50 records as per in the screen shot below:
I am returning the below JSON as per this tutorial and this resolved query:
return Json(new
{
sEcho = param.sEcho,
iTotalRecords = tracks.Count(),
iTotalDisplayRecords = filteredTracks.Count(),
aaData = results
},
JsonRequestBehavior.AllowGet);
}
This is the pagination Controller code:
var displayedTracks = filteredTracks.Skip(param.iDisplayStart).Take(param.iDisplayLength);
Here's my View code of the dataTable:
var oTable = $('#myDataTable').hide(50).fadeIn(10).dataTable({
"oLanguage": {
"sSearch": " "
},
"bAutoWidth": false,
"sAjaxSource": "Ajax_DB",
"deferRender": false,
"bServerSide": true,
"bProcessing": true,
"sScrollY": "333",
"iDisplayLength": 50,
"bPaginate": true,
"bRetrieve": true,
"bDestroy": true,
"sPaginationType": "full_numbers",
"aoColumns": [
{ "mDataProp_": "TrackID", "sWidth": "1%" },
{ "mDataProp_": "AddedDate", "bSortable": false, "sWidth": "1%" },
{ "mDataProp_": "TrackName", "sWidth": "43%" },
{ "mDataProp_": "ArtistName", "sWidth": "30%" },
{ "mDataProp_": "ArtistName", "sWidth": "30%" }
]
});
I don't know what I am doing wrong here, the pagination doesn't seem to work. Could someone please help me on how I can achive this? Thanks in advance.
Its pretty simple mate
Just change your iDisplayLength property's value to your required count i.e 100 or what ever
"iDisplayLength": 100
Refer datatables.net for documentaions which which will help you
Hope it helps
Have you sure your code looks like this :
filteredLeads = filteredLeads.OrderByDescending(orderingFunction);
var DisplayedLeads = filteredLeads.Skip(param.iDisplayStart).Take(param.iDisplayLength);
var result = from c in DisplayedLeads select new string[] { // my columns };
return Json(new
{
sEcho = param.sEcho,
iTotalRecords = leadDetails.Count(),
iTotalDisplayRecords = filteredLeads.Count(),
aaData = result
},
JsonRequestBehavior.AllowGet);
}
Let know what is your test results appearing at itotalrecords,iTotalDisplayRecords, aaData while debugging .
Hi I have a mDataProp DateTime formatting issue. Basically I want to display the date in one column and the time in another.
But as I understand it the mDataProp is directly related to your model, which does not have a time property just a adate......
Controller
var result = from a in data
select new
{
appointmentDate = a.AppointmentDate.ToShortDateString(),//.ToString("g"),
appointmentTime = a.AppointmentDate.ToLocalTime().ToString("t"),
appointmentName = a.AppointmentType.AppName,
appointmentID = a.AppointmentID
};
//Return Json data for Datatable
return Json(new
{
sEcho = param.sEcho,
iTotalRecords = total,
iTotalDisplayRecords = total,
aaData = result
});
View
<script>
$(document).ready(function () {
var urlRequest = $('#apptTable').data("request-url");
var detailRequest = $('#apptTable').data("detail-url");
$('#apptTable').dataTable({
"bSort": false,
"bServerSide": true,
"sAjaxSource": urlRequest,
"sServerMethod": "POST",
"bProcessing": true,
"bFilter": false,
"aoColumns": [
{ "mDataProp": "appointmentDate" },
{ "mDataProp": "appointmentDate" },
{ "mDataProp": "appointmentName" },
{
"mDataProp": "appointmentID",
"fnRender": function (oObj) {
return 'Details';
}
}
]
});
});
</script>
I cannot create a second variable called appointmentDate in the controller, so I'll have to format in the view.
Any ideas?
I'm fairly new to MVC and Jquery. for last couple of days I was trying to use Jqgrid http://www.trirand.com/blog/ to show data in my database. I use EF Code first to create my only class 'Author'
public class Author
{
public int AuthorID { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string FullName
{
get
{
return FirstName+ " "+LastName ;
}
}
}
and this is my 'AuthorController' which create Json data:
public ActionResult LinqGridData(string sidx, string sord, int page, int rows)
{
var jsonData = new
{
total = 5,
page = 1,
records = db.Authors.Count(),
rows = db.Authors.Select(a => new
{
id = a.AuthorID,
cell = new { a.AuthorID, a.FirstName, a.LastName }
}
)
};
return Json(jsonData, JsonRequestBehavior.AllowGet);
}
I also tried different method to get my Json data:
public ActionResult LinqGridData (string sidx, string sord, int page, int rows)
{
var jsonData = new {
total = 5,
page=1,
records = db.Authors.Count(),
rows = (from a in db.Authors
select new
{
id = a.AuthorID,
cell = new { a.AuthorID, a.FirstName, a.LastName }
}
)
};
return Json(jsonData,JsonRequestBehavior.AllowGet);
}
and here is my JavaScript, which I use in my view:
$(function () {
$("#list").jqGrid({
url: '/Author/LinqGridData',
datatype:'json',
mtype: 'GET',
colNames:['Author ID', 'First Name', 'Last Name'],
colModel:[
{name:'AuthorID',index:'AuthorID',width:55 },
{name:'FirstName',index:'FirstName',width:90 },
{name:'LastName',index:'LastName',width:80,align:'right' }
],
pager:'#pager',
rowNum: 10,
rowList:[5, 10, 20, 30],
sortname:'AuthorID',
sortorder:'desc',
viewrecords:true,
gridview:true,
caption:'Author List'
});
});
jQuery("#datagrid").jqGrid('navGrid', '#navGrid', { edit: true, add: true, del: true });
I can show the grid with dummy data. with this action method:
public ActionResult GridData(string sidx, string sord, int page, int rows)
{
var jsonData = new
{
total = 1, // we'll implement later
page = 1,
records = 3, // implement later
rows = new[]
{
new {id = 1, cell = new[] {"1", "-7", "Is this a good question?"}},
new {id = 2, cell = new[] {"2", "15", "Is that a good question?"}},
new {id = 3, cell = new[] {"3", "23", "Why is the sky in the sky?"}}
}
};
return Json(jsonData,JsonRequestBehavior.AllowGet);
}
the problem is whenever I want to show the data from my database, I only can show the grid itself not the data.
I tried to convert the json data toList() or toArary() before sending to the view, same result. I hope I made myself clear.
any help would be much appreciated.
Have you tried jsonReader with "repeatitems: false" ?
For example:
$("#list").jqGrid({
url: '/Author/LinqGridData',
datatype:'json',
jsonReader: {
repeatitems: false
},
.....
UPDATE:
If you look at the response body returned from your LinqGridData method, it looks like this:
{"total":5,"page":1,"records":1,"rows":
[
{"id":"1","cell":{"AuthorID":"1","FirstName":"Mike","LastName":"Lee"}}, .....
]
}
But I think it should be like this:
{"total":5,"page":1,"records":1,"rows":
[
{"id":"1","cell":{"1", "Mike", "Lee"}}, .....
]
}
Actually this is your "dummy data" version's response body.
I'll post my working example below. In this example, I did not use 'cell' attribute.
At server side:
var myQuery = from t in db.Customers
select t;
var jsonData = new
{
total = totalPages,
page = pageNum,
records = totalRecords,
rows = myQuery.ToList()
};
return Json(jsonData, JsonRequestBehavior.AllowGet);
At client side:
{
url: '#Url.Action("GetList")',
datatype: 'json',
jsonReader: {
repeatitems: false
},
mtype: 'GET',
colModel: [
{
name: 'CustomerID', label: 'ID', hidden: false, width: 40, sortable: true
},
{
name: 'CompanyName', label: 'Company', width: 100, align: 'center'
},
]
}
Hope this helps.
I finally managed to show data from my db. the problem was in my query. i use this method for my action method:
public JsonResult LinqGridData (string sidx, string sord, int page, object rows)
{
var authors = (from a in db.Authors select a).ToList();
var jsonData = new {
total = 5,
page=1,
records = db.Authors.Count(),
rows = authors.Select(a => new
{
id = a.AuthorID,
cell = new[] { a.AuthorID.ToString(), a.FirstName, a.LastName }
}
)
};
return Json(jsonData,JsonRequestBehavior.AllowGet);
}
and i used this in my Javascript:
$(function () {
$("#list").jqGrid({
url: "/Author/LinqGridData",
datatype: "json",
jsonReader: {
root: "rows",
page: "page",
total: "total",
records: "records",
cell: "cell",
id:"id"
},
mtype: "GET",
colNames: ["Author ID", "First Name", "Last Name"],
colModel: [
{ name: "AuthorID", key: true, width: 55 },
{ name: "FirstName", width: 80 },
{ name: "LastName", width: 100, align: "right" }
],
pager: "#pager",
rowNum: 10,
rowList: [5, 10, 20],
sortname: "AuthorID",
sortorder: "desc",
viewrecords: true,
gridview: true,
width: 610,
height: 250,
caption: "Author List"
});
});
jQuery("#list").jqGrid("navGrid", "#pager", { edit: true, add: true, del: true });
yes , you can omit the 'cell' attribute and reduce your json data. you can also put 'id':0 which normally means treat the first item as the id. i also used 'key' attribute, but it's redundant. you can also pass your query result as Array too. if anyone can tell me is there any benefit of using List over others would much appreciated.
Thanks for your help
good luck