implement datatable js in Asp.Net API server side processing - c#

I'm using datatable.js, I have table in view and API returns JSON results. I have lots of rows and i want to bind them by each page.Is there any way that datatable do it for me? I read lots of documentation but I didn't find anything useful for API
API Controller
public IHttpActionResult Get(int id)
{
return Ok(_context.Students.OrderBy(c => c.id).Skip((id - 1) * 10).Take(10).ToList());
}
Here is my table config
<script>$(document).ready(function () {
var pageindex = 1;
var table = $("#staff").DataTable({
"processing": true,
"serverSide": true,
ajax: {
url: "/Api/staffs",
dataSrc: "",
data: {
id: pageindex,
},
},
columns: [
{
data: "stf_FirstName",
},
{
data: "stf_LastName",
},
{
data: "stf_Code",
}
]
});
table.on('page', function () {
Currentpagenum();
});
function Currentpagenum() {
var info = table.page.info();
pageindex = (info.page + 1);
}
});</script>

If there are lots of rows than server side processing should be used
Try this :
HTML :
<table id="tblGrid" class="table display nowrap" style="width:100%">
</table>
JS :
function SetGrid() {
$('#tblGrid').DataTable({
"proccessing": true,
"serverSide": true,
// server side
"ajax": {
url: "/api/YourController/Method",
type: 'POST',
"data": {
Param1: Value1
}
},
// if client side
//data: YourList, // Js Array
columns: [
{ data: 'Id' },
{ data: 'Name', title: "Name" },
...
...
{ title: "Actions"},
],
"columnDefs": [
{ targets: 0, visible: false,},
],
"ordering": false,
"lengthChange": false,
"pageLength": 10,
"bDestroy": true,
"oLanguage": {
"sEmptyTable": "No Record Found"
},
});
}
Sample C# :
public object YourMethod(Param1 Value1)
{
var start = int.Parse(HttpContext.Current.Request.Form["start"]);
var result = new {
draw = HttpContext.Current.Request.Form["draw"],
recordsTotal = YourList.Count,
recordsFiltered = YourList.Count,
data = YourList.Skip(start).Take(10).ToList()
};
return result;
}

Related

Unable to display data for jQuery Datatable with server side processing

I face the issue with jQuery Datatable server-side processing in ASP.NET Core 3.1. Server-side returns data as JSON but it is not displaying in Datatable.
Below is my controller side code
public IActionResult LoadData()
{
var dict = Request.Form.ToDictionary(x => x.Key, x => x.Value.ToString());
var draw = dict["draw"];
var start = dict["start"];
var length = dict["length"];
////Find Order Column
var sortColumn = "Company";
var sortColumnDir = "asc";
int pageSize = length != null ? Convert.ToInt32(length) : 0;
int skip = start != null ? Convert.ToInt32(start) : 0;
DataSet ddata = GenralClass.GetCRMTestData((Convert.ToInt32(draw)-1)*100, 100);//GetCRMData();
ddata.Tables[0].TableName = "data";
var data = ddata;
int recordsTotal = 34790;
var jsonData = new { draw = draw, recordsFiltered = recordsTotal, recordsTotal = recordsTotal, data = data };
return Ok(JsonConvert.SerializeObject(jsonData));
}
Below is my view side code
<table class="table table-striped table-bordered table-hover dataTables-example">
<thead>
<tr>
<th style="white-space: nowrap;">Company</th>
<th style="white-space: nowrap;">Assignedto</th>
<th style="white-space: nowrap;">Provider</th>
</tr>
</thead>
</table>
Below is my Jquery Code.
$(document).ready(function () {
$('.dataTables-example').DataTable({
pageLength: 100,
processing: true,
serverSide: true,
ajax: {
url: '#Url.Action("LoadData", "SKU")',
type: 'POST',
dataType: "json",
columns: [
{ "data": "Company" },
{ "data": "Assignedto" },
{ "data": "Provider" },
]
}
});
});
I made some changes in startup.cs file in service configuration as below
public void ConfigureServices(IServiceCollection services)
{
services.AddControllersWithViews()
.AddNewtonsoftJson(options =>
{
options.SerializerSettings.Converters.Add(new StringEnumConverter());
});
services.AddControllers();
services.AddRazorPages();
services.AddDbContext<AppDbContext>(options => options.UseSqlServer(Configuration.GetConnectionString("AppDb")));
}
No error display when page load just empty table. I verify from the chrome network that data is returning from the server-side as the data attached below. I don't know what is wrong why the data is not showing. The paging number showing correct but the data is not showing. Any help.
{
"draw":"1",
"recordsFiltered":34790,
"recordsTotal":34790,
"data":{
"data":[
{
"Company":"SHAN FOODS (PVT) LTD",
"Assignedto":"Stock-Transfer",
"Provider":"Stock-Transfer"
},
{
"Company":"SHAN FOODS (PVT) LTD",
"Assignedto":"Vermicelli (150gm)",
"Provider":"030180010017"
}
]
}
}
You can change your code as follows.
LoadData:
public IActionResult LoadData()
{
//...
var jsonData = new { draw = draw, recordsFiltered = recordsTotal, recordsTotal = recordsTotal, data = data };
return new JsonResult(new {json = jsonData });
}
Jquery:
$(document).ready(function () {
$.ajax({
type: "POST",
url: "/SKU/LoadData",
data: '{}',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: OnSuccess,
});
});
function OnSuccess(response) {
$('.dataTables-example').DataTable(
{
data: response.json.data,
columns: [
{ "data": "company" },
{ "data": "assignedto" },
{ "data": "provider" },
],
});
};
Test result:
Change your json like below
{
"draw":"1",
"recordsFiltered":34790,
"recordsTotal":34790,
"data":[
{
"Company":"SHAN FOODS (PVT) LTD",
"Assignedto":"Stock-Transfer",
"Provider":"Stock-Transfer"
},
{
"Company":"SHAN FOODS (PVT) LTD",
"Assignedto":"Vermicelli (150gm)",
"Provider":"030180010017"
}
]
}

Ajax response not displaying on datatable while viewing on Firefox and Edge browsers

I have i report that displays fine on Google chrome, but while trying to view on Firefox or Edge browser, the json response displays on the browser instead of the datatable. Sample response below:
"
[{\"RegisteredBy\":\"Admin\",\"PatientRegNo\":\"De723\",\"PaymentType\":\"Cash\"}]"
I have tried including the below code:
contentType: 'application/json, charset=utf-8',
return Json(data,JsonRequestBehavior.AllowGet);
This is my Ajax function:
$("#searchBtn").click(function () {
var url = $("#frmReport").attr('action');
var str = $("#frmReport").serialize();
$("#searchBtn").prop("disabled", true);
$.ajax({
url: url,
type: "POST",
data: str,
cache: false,
dataType: "json",
success: function (_data) {
var arr = $.map(JSON.parse(_data), function (el) { return el });
table.clear();
table.destroy();
$('#tblReport').dataTable({
data: arr,
columns: [
{ "data": "RegisteredBy"},
{ "data": "PatientRegNo"},
{ "data": "PaymentType"},
],
dom: 'Bfrtip',
buttons: [
'copy', 'csv', 'excel',
{
extend: 'pdfHtml5',
orientation: 'portrait',
pageSize: 'A4'
}
]
});
}
});
table = $("#tblReport").DataTable();
});
});
My JsonResult Code:
getEntries = superAdminForBillingRepository.GetByRegNoOnly(regNo);
var data = Newtonsoft.Json.JsonConvert.SerializeObject(getEntries);
return Json(data);
I want to be able to view the ajax response on the datatable on any browser
try to invoke your table like this:
var tableTypeOfClientInfo = $('#tableTypeOfClientInfo ').DataTable({
"destroy": true,
"responsive":{
"details": {
renderer: function ( api, rowIdx, columns ) {
var data = $.map( columns, function ( col, i ) {
return col.hidden ?
'<tr data-dt-row="'+col.rowIndex+'" data-dt-column="'+col.columnIndex+'">'+
'<td>'+col.title+':'+'</td> '+
'<td>'+col.data+'</td>'+
'</tr>' :
'';
} ).join('');
return data ?$('<table/>').append( data ) :false;
}
}
},
"autoWidth": false,
"ajax": {
"url": 'some.php',
"method": 'POST',
data:{action:"SLC", categoryId:id}
},
"columns": [
{"data": "identification_number"},
{"data": "address"},
{"data": "birthday"},
{"data": "phone"},
{"data": "mail"}
],
"language":{"url": "//cdn.datatables.net/plug-ins/1.10.15/i18n/Spanish.json"},
"columnDefs": [
{
"className": "dt-center", "targets": "_all"
}
]
});

DataTable not showing JSON data

var table = $('#datatables').DataTable({
ajax: {
url: '#Url.Action("GetGrid","Vibrant", new { Area = "Marketing" })',
type: 'GET',
data: {
//filters here
columns: null,
filter: function () { return _filter; },
},
success: function (data) {
console.log("success", data);
},
error: function (data) {
console.log("error", data);
}
},
processing: true,
serverSide: true,
responsive: true,
pagingType: 'full_numbers',
language: {
search: "_INPUT_",
searchPlaceholder: "Search records",
},
columns: [
{ "data": "ID"},
{ "data": "PreviewID"},
{ "data": "EPCElement"},
{ "data": "Vibrant"}
],
method successfully returns data but the DataTable won't display it.
initialList = (from pjob in _db.PropertyJobs
select new SendVibrantOrderGridVM
{
ID = pjob.ID,
PreviewID = pjob.PreviewID,
EPCElement = pjob.EPCElement ,
Vibrant = pjob.Vibrant
}).ToList();
I am trying to populate my DataTable with the JSON Data I'd be getting within a call method.
This is a sample data returned by the GetGrid method:
{"data":[{"ID":529,"PreviewID":999992349,"EPCElement":false,"Vibrant":false}],"draw":1,"page":1,"pages":113,"length":10,"recordsTotal":1126,"recordsFiltered":1126}

jqgrid is not loading when searching by passing javascript object to asp.net webmethod

Hi tried to load the jqgrid with json by passing javascript object. but the grid is not loading.
Below is my javascript code
oSearchParam = {
InvoiceNo: document.getElementById('txtInvoiceNumber').value,
}
var grid = $("#dataGrid")[0];
//my code
$("#dataGrid").jqGrid({
// setup custom parameter names to pass to server
prmNames: {
rows: "numRows",
page: "page",
sort: "sortField",
order: "sortOrder"
},
// add by default to avoid webmethod parameter conflicts
// postData: { oSearchParam: oSearchParam },
// setup ajax call to webmethod
datatype: function (postdata) {
$(".loading").show(); // make sure we can see loader text
$.ajax({
url: 'InvoiceSearch.aspx/GetSearchResultData',
type: "POST",
contentType: "application/json; charset=utf-8",
data: JSON.stringify(postdata),
dataType: "json",
success: function (data, st) {
if (st == "success") {
var grid = $("#dataGrid")[0];
alert(data.d);
grid.addJSONData(JSON.parse(data.d));
}
},
error: function () {
alert("Error with AJAX callback");
}
});
},
// this is what jqGrid is looking for in json callback
jsonReader: {
root: "rows",
page: "page",
total: "totalpages",
records: "totalrecords",
cell: "cell",
id: "id", //index of the column with the PK in it
repeatitems: true
},
autowidth: true,
shrinkToFit: true,
height: 'auto',
colNames: ['InvoiceNo'],
colModel: [
{ name: 'InvoiceNo', index: 'InvoiceNo', width: 55, search: false }
],
rowNum: 10,
rowList: [10, 20, 30],
pager: jQuery("#pagingGrid"),
sortname: "InvoiceNo",
sortorder: "asc",
viewrecords: true,
caption: "Grid Title Here",
gridComplete: function () {
$(".loading").hide();
}
}).jqGrid('navGrid', '#pagingGrid', { edit: true, add: true, del: true },
{}, // default settings for edit
{}, // add
{}, // delete
{ closeOnEscape: true, closeAfterSearch: true }, //search
{}
)
And below is the webmethod
[WebMethod]
public static string GetSearchResultData(int? numRows, int? page, string sortField, string sortOrder, SearchParam oSearchParam)
{
DataTable dtInvoiceList = Mymethod();
var query = dtInvoiceList.AsEnumerable()
.Select(i => new SearchParam
{
InvoiceNo = i.Field<string>("InvoiceNo"),
// ImageId = i.Field<string>("DocID"),
InvoiceAmount = i.Field<decimal>("Amount"),
// ImageId = i.Field<string>("DocID"),
Status = i.Field<string>("Status"),
CurrentlyWith = i.Field<string>("CurrentlyWith")
}).ToList();
//--- setup calculations
int pageIndex = page ?? 1; //--- current page
int pageSize = numRows ?? 10; //--- number of rows to show per page
int totalRecords = query.Count(); //--- number of total items from query
int totalPages = (int)Math.Ceiling((decimal)totalRecords / (decimal)pageSize); //--- number of pages
var sortedRecords = query
.Skip((pageIndex - 1) * pageSize) //--- page the data
.Take(pageSize).ToList();
//--- format json
var jsonData = new
{
totalpages = totalPages, //--- number of pages
page = pageIndex, //--- current page
totalrecords = totalRecords, //--- total items
rows = (
from row1 in sortedRecords
select new
{
i = row1.ImageId,
cell = new string[] {
row1.InvoiceNo,
row1.Status,
row1.CurrentlyWith,
row1.InvoiceAmount.ToString(),
}
}
).ToArray()
};
string result = Newtonsoft.Json.JsonConvert.SerializeObject(jsonData);
return result;
}
My webmethod is not getting called.
Can anybody help me on this.

JSON returned from ASP.NET does not bind with Kendo grid

I can successfully make the AJAX call to my web method using the following code and web method return the JSON which is pasted below:
My Web Method
[WebMethod]
public static string GetJson()
{
string query = "SELECT top 10 cast(ClientUID as varchar) ClientUID FROM <tablename>";
SqlCommand cmd = new SqlCommand(query);
// Populate the DataSet.
DataSet data = GetData(cmd);
// return the Customers table as JSON.
DataTable dt = data.Tables[0];
var returnJSON = (from p in dt.AsEnumerable()
select new
{
ClientUID = p.Field<string>("ClientUID")
}).ToList();
var serializer = new JavaScriptSerializer();
string json = serializer.Serialize(returnJSON);
return json;
}
JSON returned by web method:
[{"ClientUID":"1"},{"ClientUID":"2"},{"ClientUID":"3"},{"ClientUID":"4"},{"ClientUID":"5"},{"ClientUID":"6"},{"ClientUID":"7"},{"ClientUID":"8"},{"ClientUID":"9"},{"ClientUID":"10"}]
Call to web method using AJAX
<script type="text/javascript">
$(document).ready(function() {
$.ajax(
{
type: "POST",
url: "ServeClientCalls.aspx/GetJson",
data: {},
contentType: "application/json;charset=utf-8",
dataType: "json",
async: true,
cache: false,
success: function(msg) {
//checking the content return from the above web method
$("#msg").html(msg.d);
//Binding to kendo Grid
$("#grid").kendoGrid({
dataSource: {
data: msg.d,
schema: {
model: {
fields: {
ClientUID: { type: "string" }
}
}
},
pageSize: 20
},
height: 430,
filterable: true,
sortable: true,
pageable: true,
columns: [
{ field: "ClientUID" }
]
});
},
error: function(x, e) {
$("#msg").html(x.responseText);
}
});
});
</script>
Problem : My grid does not bind and only headers are displayed whereas when I use the code in this manner mentioned below it is working
<script type="text/javascript">
$(document).ready(function() {
$.ajax(
{
type: "POST",
url: "ServeClientCalls.aspx/GetJson",
data: {},
contentType: "application/json;charset=utf-8",
dataType: "json",
async: true,
cache: false,
success: function(msg) {
//checking the content return from the above web method
$("#msg").html(msg.d);
**var p = [{ ClientUID: 1 }, { ClientUID: 2 }, { ClientUID: 3 }, { ClientUID: 4 }, { ClientUID: 5 }, { ClientUID: 6 }
, { ClientUID: 7 }, { ClientUID: 8 }
, { ClientUID: 9 }, { ClientUID: 10}];**
//Binding to kendo Grid
$("#grid").kendoGrid({
dataSource: {
**data: p,**
schema: {
model: {
fields: {
ClientUID: { type: "string" }
}
}
},
pageSize: 20
},
height: 430,
filterable: true,
sortable: true,
pageable: true,
columns: [
{ field: "ClientUID" }
]
});
},
error: function(x, e) {
$("#msg").html(x.responseText);
}
});
});
</script>
Use data: "d", under schema section. That should work.

Categories

Resources