Unable to display data for jQuery Datatable with server side processing - c#

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"
}
]
}

Related

How to split list of values in a jQuery datatable?

I have a datatable that includes a column that has a list of values. For example, Activity Phase Dates has a list of comma-separated dates. I cannot use render: function (data) { return moment(data).format("MM/DD/YYYY"); because a list of dates is not a valid date.
How can I split this list of dates to then apply render: function (data) { return moment(data).format("MM/DD/YYYY");? I have tried split(','), but it does not work. Most likely because this list of values is not a string. I also tried replace(',', ' '), but also did not work for probably the same reason.
Actions:
public JsonResult LoadApplications()
{
return Json(new { data = GetApplications("") }, JsonRequestBehavior.AllowGet);
}
private IEnumerable GetApplications(string keyword)
{
var applications = from a in _db.Applications
where a.AppNumber.ToString().Contains(keyword)
|| a.NonCityMortgageDate.ToString().Contains(keyword)
|| a.ApplicationActivityPhas.Any(d => d.ActivityPhaseDate.ToString().Contains(keyword))
select new
{
a.AppNumber, a.NonCityMortgageDate,
ActivityPhaseDates = a.ApplicationActivityPhas.Select(d => d.ActivityPhaseDate).ToList(),
a.Id
};
return applications;
}
DataTable:
$(document).ready(function () {
$("#ApplicationDataTable").DataTable({
ajax: {
url: '#Url.Action("LoadApplications", "Application")',
datatype: "json",
type: "GET"
},
columns: [
{
data: "AppNumber",
render: function (data, type, row) {
var applicationDetails = '#Url.Action("Details", "Application")/' + row.Id;
return '' + data + '';
}
},
{
data: "NonCityMortgageDate",
type: "date",
render: function (data) {
if (data != null) {
return moment(data).format("MM/DD/YYYY");
}
else {
return "";
}
}
},
{
data: "ActivityPhaseDates",
type: "date",
render: function (data) {
return moment(data).format("MM/DD/YYYY");
}
},
{ data: "Id" }
]
});
});
Index:
<div class="pt-2">
<table class="table table-bordered table-sm" id="ApplicationDataTable">
<thead class="table-info">
<tr>
<th>Application Number</th>
<th>Non City Mortgage Date</th>
<th>Activity Phase Dates</th>
<th>Id</th>
</tr>
</thead>
</table>
</div>
The following is a solution:
{
data: "ActivityPhaseDates",
render: function (data) {
var activityPhaseDates = "";
for (var i = 0; i < data.length; i++) {
activityPhaseDates += moment(data[i]).format("MM/DD/YYYY") + " ";
}
return activityPhaseDates;
}
}
The output is:
03/14/2022 03/31/2022 03/31/2022 03/31/2022 03/31/2022

How to prefilter a jQuery DataTable?

I need to create a datatable that only displays records that have only one Activity Phase equal to "Waiting". Currently, the following solution displays all records, some of which have multiple Activity Phases. The first Activity Phase in the workflow is "Waiting".
Actions:
public JsonResult LoadWaitList()
{
return Json(new { data = GetWaitList() }, JsonRequestBehavior.AllowGet);
}
private IEnumerable GetWaitList()
{
var waitList = from a in _db.Applications
select new
{
a.AppNumber, ApplicationType = a.ApplicationType.Label,
ActivityPhases = a.ApplicationActivityPhas.Select(p => p.ActivityPhas.ActivityPhase).ToList(),
a.Id
};
return waitList;
}
DataTable:
$("#WaitListDataTable").DataTable({
ajax: {
url: '#Url.Action("LoadWaitList", "Application")',
datatype: "json",
type: "GET"
},
columns: [
{
data: "AppNumber",
render: function (data, type, row) {
var applicationDetails = '#Url.Action("Details", "Application")/' + row.Id;
return '' + data + '';
}
},
{ data: "ApplicationType" },
{ data: "ActivityPhases" },
{ data: "Id" }
]
});
Index Table:
<div class="pt-2">
<table class="table table-bordered table-sm" id="WaitListDataTable">
<thead class="table-info">
<tr>
<th>Application Number</th>
<th>Application Type</th>
<th>Activity Phase</th>
<th>Id</th>
</tr>
</thead>
</table>
</div>
Since "Waiting" is the first activity phase in the workflow, to display application records that only have one activity phase equal to "Waiting", I added the following:
public JsonResult LoadWaitList()
{
return Json(new { data = GetWaitList() }, JsonRequestBehavior.AllowGet);
}
private IEnumerable GetWaitList()
{
var waitList = (from a in _db.Applications
select new
{
a.AppNumber, ApplicationType = a.ApplicationType.Label,
ActivityPhases = a.ApplicationActivityPhas.Select(p => p.ActivityPhas.ActivityPhase).ToList(),
a.Id
}).Where(p => p.ActivityPhases.Count() == 1);
return waitList;
}

implement datatable js in Asp.Net API server side processing

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;
}

Post Action in Partial View Not Triggered

Hi i am still learning MVC. I have a requirement where i have a page with dropdownlist with table name. When the user chooses the table name, a partial view will be called to display the data in DataTable.
Currently, i am having an issue when trying to display the DataTable. The post action, GetDPUserList() is not triggered thus the data is not showing.
Here is how i call my partial view:
$('#ddPatchingAction').change(function () {
ddPatchingActionValue = $('#ddPatchingAction option:selected').val();
if (ddPatchingActionValue) {
$.get("/PatchingBatch/DataTableBatch", function (data) {
$('#divPatching').html(data);
$('#batchTable').DataTable();
});
}
});
Here is the partial view:
<table id="batchTable" class="table-striped table-responsive">
<thead>
<tr>
<th>Username</th>
<th>Name</th>
<th>Email Address</th>
<th>Is Admin</th>
<th></th>
</tr>
</thead>
</table>
<link href="//cdn.datatables.net/1.10.19/css/jquery.dataTables.min.css" rel="stylesheet" />
<link href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet" integrity="sha384-wvfXpqpZZVQGK6TAh5PVlGOfQNHSoD2xbE+QkPxCAFlNEevoEH3Sl0sibVcOQVnN" crossorigin="anonymous">
#section scripts{
<script src="//cdn.datatables.net/1.10.19/js/jquery.dataTables.min.js"></script>
<script>
var popup, dataTable;
$(document).ready(function () {
dataTable = $("#batchTable").DataTable({
"ajax": {
"url": "/PatchingBatch/GetDPUserList",
"type": "POST",
"datatype": "json"
},
"columns": [
{ "data": "Username", "name":"Username" },
{ "data": "Name", "name": "Name" },
{ "data": "Email", "name": "Email" },
{ "data": "IsAdmin", "name": "IsAdmin" },
{
"data": "DPUserID", "render": function (data) {
return "<a class='btn btn-primary btn-sm' onclick=EditUserForm('#Url.Action("UpdateUser", "Account")/" + data +"')><i class='fa fa-pencil'></i> Edit</a><a class='btn btn-danger btn-sm' style='margin-left: 5px' onclick=Delete(" + data +")><i class='fa fa-trash'></i> Delete</a>";
},
"orderable": false,
"searchable": false,
"width": "150px"
},
],
"processing": "true",
"serverSide": "true",
"order": [0, "asc"]
});
});
function AddUserForm(url) {
var formDiv = $('<div/>');
$.get(url)
.done(function (response) {
formDiv.html(response);
popup = formDiv.dialog({
autoOpen: true,
resizable: false,
title: "Add User Account",
height: 250,
width: 300,
close: function () {
popup.dialog('destroy').remove();
}
});
});
}
function EditUserForm(url) {
var formDiv = $('<div/>');
$.get(url)
.done(function (response) {
formDiv.html(response);
popup = formDiv.dialog({
autoOpen: true,
resizable: false,
title: "Update User Account",
height: 410,
width: 300,
close: function () {
popup.dialog('destroy').remove();
}
});
});
}
function SubmitForm(form) {
$.validator.unobtrusive.parse(form);
if ($(form).valid()) {
$.ajax({
type: "POST",
url: form.action,
data: $(form).serialize(),
success: function (data) {
if (data.success) {
popup.dialog('close');
dataTable.ajax.reload();
$.notify(data.message, {
globalPosition: "top center",
className: "success"
})
}
}
});
}
return false;
}
function Delete(id) {
if (confirm("Are you sure you want to delete this data?")) {
$.ajax({
type: "POST",
url: '#Url.Action("DeleteUser", "Account")/' + id,
success: function (data) {
if (data.success) {
dataTable.ajax.reload();
$.notify(data.message, {
globalPosition: "top center",
className: "success"
})
}
}
}
)
}
}
</script>
}
Here is the controller:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Mvc;
using MVCWeb.Models;
using System.Linq.Dynamic;
namespace MVCWeb.Controllers
{
public class PatchingBatchController : Controller
{
// GET: PatchingBatch
public ActionResult DataTableBatch()
{
return PartialView();
}
[HttpPost]
public ActionResult GetDPUserList()
{
//server side parameter
int start = Convert.ToInt32(Request["start"]);
int length = Convert.ToInt32(Request["length"]);
string searchValue = Request["search[value]"];
string sortColumnName = Request["columns[" + Request["order[0][column]"] + "][name]"];
string sortDirection = Request["order[0][dir]"];
List<DP_User> userList = new List<DP_User>();
using (DBModel db = new DBModel())
{
userList = db.DP_User.ToList<DP_User>();
userList = userList.ToList<DP_User>();
int totalrows = userList.Count();
//search
if (!string.IsNullOrEmpty(searchValue))
{
userList = userList.Where(x => (x.Username != null && x.Username.ToString().ToLower().Contains(searchValue)) ||
(x.Name != null && x.Name.ToString().ToLower().Contains(searchValue)) ||
(x.Email != null && x.Email.ToString().ToLower().Contains(searchValue))).ToList<DP_User>();
}
int totalrowsafterfilter = userList.Count();
//sorting
if (!string.IsNullOrEmpty(sortColumnName) && !string.IsNullOrEmpty(sortDirection))
{
userList = userList.OrderBy(sortColumnName + " " + sortDirection).ToList<DP_User>();
}
//paging
userList = userList.Skip(start).Take(length).ToList<DP_User>();
return Json(new { data = userList, draw = Request["draw"], recordsTotal = totalrows, recordsFiltered = totalrowsafterfilter },
JsonRequestBehavior.AllowGet);
}
}
}
}
I have checked in chrome console, but there is no error. So i am not sure what is the problem. Is there something wrong with my code? Please help. Thank you.

Populating Jquery Datatables with Webservice

i have created a webservice in Asp.net which is returning the following
<string xmlns="http://tempuri.org/">[{"Id":13,"FirstName":"Mohsin","LastName":"Mustufa","Birthday":"12/11/1990","Phone":null,"Email":"abcd#yahoo.com","UserId":"11"}]
now i want to populate that data in Jquery Datatable
here is the HTML
<table id="example" class="display" cellspacing="0" width="100%">
<thead>
<tr>
<th>Id</th>
<th>FirstName</th>
<th>LastName</th>
<th>Birthday</th>
<th>Phone</th>
<th>Email</th>
<th>UserId</th>
</tr>
</thead>
<tfoot>
<tr>
<th>Id</th>
<th>FirstName</th>
<th>LastName</th>
<th>Birthday</th>
<th>Phone</th>
<th>Email</th>
<th>UserId</th>
</tr>
</tfoot>
</table>
Jquery
$.ajax({
type: 'POST',
url: 'ws.asmx/ContactsList',
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
//alert(data.d);
$('#example').dataTable({
"aaData": data.d,
"aoColumns": [
{
"mDataProp": "Id"
}, {
"mDataProp": "FirstName"
}, {
"mDataProp": "LastName"
}, {
"mDataProp": "Birthday"
}, {
"mDataProp": "Phone"
}, {
"mDataProp": "Email"
}, {
"mDataProp": "UserId"
}
]
});
}});
here data.d is showing the following when console.log is called
[{"Id":13,"FirstName":"Mohsin","LastName":"Mustufa","Birthday":"12/11/1990","Phone":null,"Email":"abcd#yahoo.com","UserId":"11"}]
webservice
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public string ContactsList()
{
var contacts = new List<ContactsModel>();
var conn = ConfigurationManager.ConnectionStrings["AccountsConnectionString"].ConnectionString;
using (var con = new SqlConnection(conn))
{
con.Open();
const string query = "SELECT [Id], [F_name], [L_name], [Phone], [Birthday], [Email], [User_id] FROM [Contacts]";
var cmd = new SqlCommand(query, con);
var reader = cmd.ExecuteReader();
while (reader.Read())
{
var model = new ContactsModel();
model.Id = Convert.ToInt32(reader["Id"].ToString());
model.FirstName = reader["F_name"].ToString();
model.LastName = reader["L_name"].ToString();
model.Birthday = reader["Birthday"].ToString();
model.Email = reader["Email"].ToString();
model.UserId = reader["User_id"].ToString();
contacts.Add(model);
}
}
return new JavaScriptSerializer().Serialize(contacts);
}
Error
Request Unknown parameter 'Id' for Row 0
Seems that data returned by the web service are interpreted as string. Try to use JSON.parse(data.d)
http://plnkr.co/edit/JGzCNT6Zg73xtFwAUuOx?p=preview
$(document).ready(function() {
var data = {
d : '[{"Id":13,"FirstName":"Mohsin","LastName":"Mustufa","Birthday":"12/11/1990","Phone":null,"Email":"abcd#yahoo.com","UserId":"11"}]'
};
$('#example').dataTable({
"aaData": JSON.parse(data.d),
"aoColumns": [
{
"mDataProp": "Id"
}, {
"mDataProp": "FirstName"
}, {
"mDataProp": "LastName"
}, {
"mDataProp": "Birthday"
}, {
"mDataProp": "Phone"
}, {
"mDataProp": "Email"
}, {
"mDataProp": "UserId"
}
]
});
} );

Categories

Resources