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}
Related
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;
}
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"
}
]
});
I am not able to retrieve data in datatable using datatable.js. The Json response is a string but in the output I get every character of the string in each row rather that jst two entries.
Please help. Thanks in advance
function fillGrid() {
$.ajax({
type: 'POST',
url: 'BehindCode/client.aspx/fillgrid',
cache: false,
dataType: "json",
contentType: "application/json; charset=utf-8",
beforeSend: function () {
$('#gridLoadingDiv').attr('style', 'display:block');
},
complete: function () {
$('#gridLoadingDiv').attr('style', 'display:none');
},
data: "{}",
success: function (data) {
data = data.d;
alert(data);
$("#clientTable").DataTable({
"searching": true,
"processing": true,
"data": data,
"columns": [{
"title": "CLIENT NAME"
}]
});
}
});
}
C# code..from where data is being retreived..
[WebMethod]
public static string fillgrid()
{
BehindCode_client client = new BehindCode_client();
string strfetch = "SELECT CLIENT_NAME FROM k_client_master";
string aadata = "";
client.ds = client.DEngine.GetDataSet(strfetch, "Data", client.conn);
if (client.ds != null && client.ds.Tables[0].Rows.Count > 0)
{
aadata = JsonConvert.SerializeObject(client.ds);
// aadata = "{'draw':1, 'recordsTotal':2, 'recordsFiltered':2, 'data':[{'CLIENT_NAME': 'Pyrotech'},{'CLIENT_NAME':'Workspace'}]}"; // tried this also
// aadata = "{'data':[{'CLIENT_NAME': 'Pyrotech'}, {'CLIENT_NAME':'Workspace'}]}"; // tried this as well
}
return (aadata.Replace("'","\""));
}
}
JSON Response as in developer tools
Output in datatable
enteries in database which are retreived
I'm not familiar with C# but on the JavaScript part you're not decoding the JSON data.
Try this:
success: function (data) {
data = JSON.parse(data.d).Data;
alert(data);
$("#clientTable").DataTable({
"searching": true,
"processing": true,
"data": data,
"columns": [
{data: "CLIENT_NAME"}
]
});
}
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.
Ok. I have several JQuery Ajax posts, which are calling individual WebMethods. I've come across an issue, and i now need to combine the webmethods into one, but then still be able to split out the return values according to the list. So for example, I need something that returns multiple lists, so that my Ajax call, can then render the respective Jquery Datatables like: table 1 = drList[0], table 2 =drList[1] etc.
Webmethod code is below:
[WebMethod]
[ScriptMethod]
public static List<GlobalClasses.ValueDateSummary> GetValueDateSummary()
{
string TSQL = "SELECT * FROM vw_view1 WHERE (SenderBIC ='" + HttpContext.Current.User.Identity.Name + "') ORDER BY ValueDate DESC";
DataTable dtValueDateSummary = null;
GlobalClasses.ValueDateSummary objSummary;
SqlConnection conn = new SqlConnection(WebConfigurationManager.ConnectionStrings["MIReporting"].ConnectionString);
using (conn)
{
conn.Open();
using (SqlDataAdapter sqlAdapter = new SqlDataAdapter(TSQL, conn))
{
dtValueDateSummary = new DataTable();
sqlAdapter.Fill(dtValueDateSummary);
}
}
List<GlobalClasses.ValueDateSummary> drList = new List<GlobalClasses.ValueDateSummary>();
foreach (DataRow row in dtValueDateSummary.Rows)
{
objSummary = new GlobalClasses.ValueDateSummary();
objSummary.fld1= row["1"].ToString();
objSummary.fld2 = row["2"].ToString();
objSummary.fld3 = row["3"].ToString();
objSummary.fld5 = row["4"].ToString();
drList.Add(objSummary);
}
return drList;
}
the only difference between this and the other webmethod call is the view being used.
the Ajax call is :
$.ajax({
type: 'POST',
url: 'Default.aspx/GetValueDateSummary',
data: '{}',
contentType: 'application/json;charset=utf-8',
dataType: 'json',
success: function (response) {
renderMsgSummary(response.d);
},
error: function (errMsg) {
$('#errorMessage').text(errMsg);
}
})
the renderMsgSummary is the Jquery datatable, so this need to be as follows:
renderMsgSummary(response.d[0]);
renderOtherTable(response.d[1]);
OK - almost there, trying to merge the client side script in now.
<script type="text/javascript">
$(document).ready(function () {
function renderMsgVal(result) {
var dtMsgValData = [];
$.each(result, function () {
dtMsgValData.push([
this.SenderBIC,
this.ValueDate,
this.MessageType,
this.Reference
]);
});
function renderMsgSummary(result) {
var dtMsgSumData = [];
$.each(result, function () {
dtMsgSumData.push([
this.SenderBIC,
this.MessageDate,
this.MessageType,
this.Count
]);
});
$('#tblValueDateSummary').dataTable({
"aaData": dtMsgValData,
"aLengthMenu": [[10, 25, 50, 100, -1], [10, 25, 50, 100]]
'asStripClasses': null,
"iDisplayLength": 10,
//"aaSorting": [[0, "asc"]],
"bJQueryUI": true,
"bFilter": true,
"bAutoWidth": false,
"bProcessing": true,
// "sDom": 'RC<"clear">lfrtip',
"sDom": 'RC<"H"lfr>t<"F"ip>',
//Scrolling .......
"sScrollY": "250px",
"sScrollX": "100%",
"sScrollXInner": "100%",
"bScrollCollapse": true,
//Dynamic Language .......
"oLanguage": {
//"sZeroRecords": "There are no messages that match your,
"sLengthMenu": "Display _MENU_ records per,
"sInfo": "Displaying _START_ to _END_ of _TOTAL_ records",
"sInfoEmpty": "Displaying _START_ to _END_ of _TOTAL_m
"sInfoFiltered": "(filtered from _MAX_ total records)",
"sEmptyTable": 'No Rows to display.....!',
"sSearch": "Search all columns:",
"sLoadingRecords": "Please wait - loading..."
},
"oSearch": {
"sSearch": "",
"bRegex": false,
"bSmart": true
}
});
$('#tblMessageDateSummary').dataTable({
"aaData": dtMsgSumData,
"aLengthMenu": [[10, 25, 50, 100, -1], [10, 25, 50, 100]]
"asStripClasses": null,
"iDisplayLength": 10,
"aaSorting": [[0, "asc"]],
"bJQueryUI": true,
"bFilter": true,
"bAutoWidth": true,
"bProcessing": true,
"sDom": 'RC<"clear">lfrtip',
//"sDom": '<"F"ip>l',
//Scrolling .......
"sScrollY": "250px",
"sScrollX": "100%",
"sScrollXInner": "100%",
"bScrollCollapse": true,
//Dynamic Language .......
"oLanguage": {
// "sZeroRecords": "There are no messages that match your,
"sLengthMenu": "Display _MENU_ records per,
"sInfo": "Displaying _START_ to _END_ of _TOTAL_ records",
"sInfoEmpty": "Showing 0 to 0 of 0 records",
"sInfoFiltered": "(filtered from _MAX_ total records)",
"sEmptyTable": 'No Rows to display.....!',
"sSearch": "Search all columns:"
},
"oSearch": {
"sSearch": "",
"bRegex": false,
"bSmart": true
}
});
}
$.ajax({
type: 'POST',
url: 'Default.aspx/GetMessageDetails',
data: '{}',
contentType: 'application/json;charset=utf-8',
dataType: 'json',
success: function (response) {
//console.log(response);
//alert(response.d);
renderMsgVal(response.d[0]);
renderMsgSummary(response.d[1]);
},
error: function (errMsg) {
$('#errorMessage').text(errMsg);
}
});
</script>
not sure if this is possible?
If I understand correctly, you can return a List of Lists.
public static List<List<GlobalClasses.ValueDateSummary>> GetValueDateSummary()
{
var allLists = new List<List<GlobalClasses.ValueDateSummary>>();
foreach (DataRow row in dtValueDateSummary.Rows)
{
objSummary = new GlobalClasses.ValueDateSummary();
objSummary.fld1= row["1"].ToString();
objSummary.fld2 = row["2"].ToString();
objSummary.fld3 = row["3"].ToString();
objSummary.fld5 = row["4"].ToString();
drList.Add(objSummary);
}
allLists.Add(drList);
//add other lists to allLists
//..
return allLists;
}
wrap your various lists into a bigger class i.e.
make a class something like
public class Wrapper
{
public List<GlobalClasses.ValueDateSummary> list1 {get;set;}
public List<GlobalClasses.ValueDateSummary> list2 {get;set;}
public List<SomeOtherClassCollectino> list3{get;set;}
}
and return this wrapper in your webmethod i.e.
[WebMethod]
[ScriptMethod]
public static List<GlobalClasses.ValueDateSummary> GetValueDateSummary()
{
// your db logic
Wrapper wrapper = new Wrapper();
List<GlobalClasses.ValueDateSummary> drList = new List<GlobalClasses.ValueDateSummary>();
foreach (DataRow row in dtValueDateSummary.Rows)
{
objSummary = new GlobalClasses.ValueDateSummary();
objSummary.fld1= row["1"].ToString();
objSummary.fld2 = row["2"].ToString();
objSummary.fld3 = row["3"].ToString();
objSummary.fld5 = row["4"].ToString();
drList.Add(objSummary);
}
wrapper.list1 = drList;
//similarly fetch other lists
//wrapper.list2 = drList2;
return new JavaScriptSerializer().Serialize(wrapper);
}
and on the client side you can access it like:
var jsonData = $.parseJSON(msg.d);
renderMsgSummary(jsonData.list1);
renderMsgSummary(jsonData.list2);