i'm hoping someone can help me...
I am a little new to jquery and datatables but I have the following datatable that I am able to create a hyper-link in column[1] when the table is rendered using 'mRender' as seen in the examples:
however i would like the 'id' part of the hyper link to come from the 'mData' of column[0] and display the mData associated with column[1] when the table is rendered.
here is my DataTable;
var oTable = $('#allCustomerSummary').dataTable({
//"aaSorting": [[4, "desc"]],
"sAjaxSource": '/GetMyDataLink/CustRel',
"aoColumns": [
{ "mData": "ID" },
{ "mData": "OrganizationName" },
{ "mData": "ContactCount" },
{ "mData": "AccountCount" },
{ "mData": "FacilityCount" },
{ "mData": "HasParentOrg" },
{ "mData": "IsParentOrg" }
],
"aoColumnDefs": [
{ "bvisible": false, "atargets": [0] },
{
"aTargets": [1],
"mData": "ID",
"mRender": function (data, type, full) {
return '' + data + '';
}
}
],
"sDom":'<p><"pull-left" Cfr>t<"F"i>',
"oLanguage": { "sSearch": "" },
"bScrollInfinite": false,
"iDisplayLength": 15
});
Any help would gladly be appreciated :)
I believe the full argument to the mRender function is the entire row's data, so try:
"mRender": function (data, type, full) {
return '' + data + '';
}
Related
I am using ASP.NET; I am getting the data from the backend as expected, but it is not showing in the web page using a datatable.
Web page:
#{
ViewBag.Title = "Employee";
}
<h2>Employee List</h2>
<table id="myTable">
<thead>
<tr>
<th>EmployeeId</th>
<th>Name</th>
<th>Age</th>
<th>Position</th>
</tr>
</thead>
</table>
JavaScript portion of code (jQuery)
$(document).ready(function () {
$('#myTable').DataTable({
processing:true,
"ajax": {
"url": "/Employee/GetList",
"type": "GET",
"dataType": "json",
"success": function (msg) {
console.log(msg.data);
},
"failure": function (response) {
alert(response);
},
"error": function (response) {
alert(response);
}
},
"columns": [
{ data: "EmployeeId" },
{ data: "Name" },
{ data: "Age" },
{ data: "Position"},
]
});
});
Here is the response I am getting from the backend. This is the data I copied from Netword -> Response tab against the endpoint I call to fetch the data
{
"data": [
{
"EmployeeId": 1,
"Name": "Dhruv",
"Age": 23,
"Position": "Full Stack Developer"
},
{
"EmployeeId": 2,
"Name": "Soni",
"Age": 21,
"Position": "DBA"
},
{
"EmployeeId": 3,
"Name": "Mike",
"Age": 24,
"Position": "Frontend Developer"
},
{
"EmployeeId": 4,
"Name": "Bob",
"Age": 20,
"Position":"SRE"
}
]
}
I am trying to get the data from database and show it to the user using a datatable. I am successfully getting the response back from the database, but the data is not showing inside the table. And I can't figure it out why....
Update:3
Controller:
public ActionResult GetList()
{
var empList = new List<Employee>()
{
new Employee(){ EmployeeId = 1, Name = "A", Age = 19, Position = "Engineer-I"},
new Employee(){ EmployeeId = 2, Name = "B", Age = 20, Position = "Engineer-II"},
new Employee(){ EmployeeId = 3, Name = "C", Age = 21, Position = "Engineer-I"},
new Employee(){ EmployeeId = 4, Name = "D", Age = 22, Position = "Engineer-III"},
};
return Json(new { data = empList }, JsonRequestBehavior.AllowGet);
}
Note: You even can directly return Json(new { empList }) in that case, in your HTML-Ajax you only have to write return msg; not msg.data
View:
<h2>Employee List</h2>
<table id="myTable">
<thead>
<tr>
<th>EmployeeId</th>
<th>Name</th>
<th>Age</th>
<th>Position</th>
</tr>
</thead>
</table>
#section scripts {
<script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.2.1.min.js"></script>
<script src="https://cdn.datatables.net/1.11.3/js/jquery.dataTables.min.js"></script>
<script>
$(document).ready(function () {
$('#myTable').DataTable({
processing: true,
"ajax": {
"type": "GET",
"url": "/DatatableInAnotherWay/GetList",
"dataSrc": function (msg) {
console.log(msg.data);
return msg.data;
}
},
"columns": [
{ "data": "employeeId" },
{ "data": "name" },
{ "data": "age" },
{ "data": "position" },
]
});
});
</script>
}
Note: I am returning as return Json(new { data = empList }); so I would receive response as msg.data. Check the response in your browser console as below:
Importantly, be sure about the column case as you can see I am getting it as lower-case so I bind them as like this"data": "employeeId". As you are saying you are getting in Upper-Case as EmployeeId you should then bind as "data": "EmployeeId"
Final Output:
Special Note:
Remember these words forver, If you want to be a great programmer, you must concentrate on :
Debugging
Code readability
Self reading/teaching attitude
Update:2
If you still want to persist with your code: You could do as following:
$('#myTable').DataTable({
processing: true,
"ajax": {
"type": "GET",
"url": "/Employee/GetList",
"dataSrc": function (msg) {
return msg;
}
},
"columns": [
{ "data": "EmployeeId" },
{ "data": "Name" },
{ "data": "Age" },
{ "data": "Position" },
]
});
Issue on your code:
You were defining the column in worng way: you should do it in following way:
"columns": [
{ "data": "EmployeeId" },
{ "data": "Name" },
{ "data": "Age" },
{ "data": "Position" },
]
Update:2 Output:
Update:
Based on your updated question, its clearly seen that you are ajax calling pattern is incorrect. How your msg.data would be bounded into your "columns": no way. Please try my updated code. Just copy and paste.
I am successfully getting the response back from the database but the
data are not showing inside the table. And i can't figure it out why?
It's because of your row definition in your columns within the datatable.
You would define all of your data members in lower case - like
"columns": [
{ data: "employeeId" },
{ data: "name" },
{ data: "age" },
{ data: "position"},
]
Note: UpperCase EmployeeId, Name etc in jQuery datatable are causing parsing issues. In addition, please follow the $.ajax({}); calling format as per my demo for better code readability.
Complete example:
<table id="myTable" class="table table-striped table-bordered dt-responsive nowrap" width="100%" cellspacing="0">
<thead>
<tr>
<th>ID</th>
<th>Name</th>
<th>Age</th>
<th>Position</th>
</tr>
</thead>
</table>
#section scripts {
<script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.2.1.min.js"></script>
<script src="https://cdn.datatables.net/1.11.3/js/jquery.dataTables.min.js"></script>
<script>
$(document).ready(function () {
$.ajax({
type: "GET",
url: "/Employee/GetList",
success: function (response) {
$('#myTable').DataTable({
data: response,
columns: [
{ data: 'EmployeeId' },
{ data: 'Name' },
{ data: 'Age' },
{ data: 'Position' }
]
});
},
error: function (response) {
alert(response.responseText);
}
});
});
</script>
}
Output:
I'm trying to bind jQuery DataTable by calling mvc action method using AJAX call and trying to populate the table using JSON data but it gets stuck on loading. Am I missing something?
Also, how can I implement server side Paging, Searching and Sorting in jQuery DataTable.
function initDataTable(ClientId)
{
var assetListVM;
$(function () {
assetListVM = {
dt: null,
init: function () {
var ClientId = $('#ddlClient').val();
dt = $('#records-data-table').dataTable({
"serverSide": true,
"processing": true,
"ajax": {
"type": "POST",
"dataType": "json",
"url": "#Url.Action("GetProcessingData", "Processing")?clientId=" + ClientId,
"success": function (data) {
alert(data);
console.log(data);
},
"error": function(){
alert("Error");
}
},
"columns": [
{ "title": "Co Num",
"data": "CompanyNo",
"searchable": true },
{ "title": "Cycle Date",
"data": "CycleDate",
"searchable": true },
{ "title": "Policy Number",
"data": "PolicyNo",
"searchable": true },
{ "title": "Issue Date",
"data": "IssueDate",
"searchable": true },
{ "title": "Transaction Date",
"data": "TransactionDate"
},
{ "title": "Transaction Amt",
"data": "TransactionAmount"
},
{ "title": "Item Code",
"data": "ItemCode"
},
{ "title": "Account",
"data": "Account"
},
{ "title": "Owner Name",
"data": "OwnerName"
}
],
"lengthMenu": [[10, 25, 50, 100], [10, 25, 50, 100]],
});
}
}
// initialize the datatables
assetListVM.init();
});
}
Below is my action method:
public ActionResult GetProcessingData(int clientId)
{
ClientSummary ClientSUM = new ClientSummary();
List<PolicyDownload> LstPData = new List<PolicyDownload>();
DataTable dtProcessingData = new DataTable();
try
{
using (DLpolicyDownload objDLpolicyDownload = new DLpolicyDownload())
{
dtProcessingData = objDLpolicyDownload.GetProcessingRecordDetails(clientId);
if (dtProcessingData != null)
{
foreach (DataRow dr in dtProcessingData.Rows)
{
PolicyDownload pData = new PolicyDownload();
pData.CompanyNo = Convert.ToInt32(dr["CO_NUM"]);
pData.CycleDate = Convert.ToString(dr["CYCLE_DATE"]);
pData.PolicyNo = Convert.ToString(dr["POLICY_NUMBER"]);
pData.IssueDate = Convert.ToString(dr["ISSUE_DATE"]);
pData.TransactionDate = Convert.ToString(dr["TRANSACTION_DATE"]);
pData.TransactionAmount = Convert.ToDouble(dr["TRANSACTION_AMOUNT"]);
pData.ItemCode = Convert.ToInt32(dr["ITEM_CODE"]);
pData.Account = Convert.ToString(dr["ACCOUNT"]);
pData.OwnerName = Convert.ToString(dr["OWNER_NAME"]);
LstPData.Add(pData);
}
}
}
}
catch (Exception ex)
{
if (logChoice)
{
log.Error(ex.Message, ex);
}
}
var data = from s in LstPData
select s;
return Json(new { data = data }, JsonRequestBehavior.AllowGet);
}
Below is the JSON output of this action method:
{"data":[{"PolicyDownloadID":0,"ImportDate":null,"CycleDate":"10/23/2017","CompanyID":0,"CompanyNo":40,"PolicyNo":"L0000001","PlanCode":null,"InsuranceType":null,"IssueDate":"05/02/2011","TransactionDate":"08/03/2017","TransactionAmount":7545.59,"ItemCode":0,"Account":"SBEN","Mode":null,"ModeAmount":0,"PayerName":null,"OwnerName":"CERNY, RAYMOND C","InsuredName":null,"PayeeName":null,"JointOwner":null,"SBC":0,"SBCAmount":0,"IsActive":false,"CreatedOn":"\/Date(-62135575200000)\/"},{"PolicyDownloadID":0,"ImportDate":null,"CycleDate":"10/23/2017","CompanyID":0,"CompanyNo":6,"PolicyNo":"FGL01234","PlanCode":null,"InsuranceType":null,"IssueDate":"07/23/2010","TransactionDate":"08/02/2017","TransactionAmount":26999.62,"ItemCode":0,"Account":"SBEN","Mode":null,"ModeAmount":0,"PayerName":null,"OwnerName":"BURNHAM, STEVEN L","InsuredName":null,"PayeeName":null,"JointOwner":null,"SBC":0,"SBCAmount":0,"IsActive":false,"CreatedOn":"\/Date(-62135575200000)\/"}]}
Below is the screenshot where it stuck:
It is calling my action method but unable to bind the JSON data.
success function - Must not be overridden as it is used internally in DataTables.
So remove success function and try once, hope it will help you.
DataTables requires json in certain format, look at Ajax tab in DataTables Documentation. Your answer in action don't corresponds to this format.
Try to add wrapper class (real or anonymous) with "data" field, which will be your list of objects.
Few things to take care while implementing server side datatable:
Your datatable in view must match number of columns coming with data.
The column names which you are mentioning in datatable should be same as in database table.
For implementing server side searching, add in a row textboxes below header row for each column. you need to bind each textbox keyup event for relevent column and pass it to server and rebind datatable
I want to send custom object to my controller method with jquery datatables default parameters for paging, sorting, searching and # of records binding.
The issue is :
When I Post object to server using datatable ajax it successfully post my object and also send parameters for length, start and draw BUT stops sending parameters for sorting n searching.
When I do GET request it sends all parameters but not only my custom object and obviously it should not
I want to send custom object with datatable defaults parameters for paging and sorting
WHAT IS THE SOLUTION FOR IT ?
here is code:
$('#example').DataTable({
"processing": true,
"serverSide": true,
"ajax": {
"url": "/Color/Fetch",
"type": 'Post',
// "dataType": "json"
data: { color: $scope.colorSearch }
// dataSrc: 'data'
},
"columns": [
{ "data": "Active" },
{ "data": "Company_Id" },
{ "data": "Id" },
{ "data": "IsActive" },
{ "data": "Name" }
]
});
Controller action:
public JsonResult Fetch(Color color, int draw, int start, int length)
{
string search = Request.QueryString["search[value]"];
int sortColumn = -1;
string sortDirection = "asc";
if (length == -1)
{
length = 90;
}
// note: we only sort one column at a time
if (Request.QueryString["order[0][column]"] != null)
{
sortColumn = int.Parse(Request.QueryString["order[0][column]"]);
}
if (Request.QueryString["order[0][dir]"] != null)
{
sortDirection = Request.QueryString["order[0][dir]"];
}}
Try to use the following approach:
$('#example').DataTable({
"processing": true,
"serverSide": true,
/*
"ajax": {
"url": "/Color/Fetch",
"type": 'Post',
// "dataType": "json"
data: { color: $scope.colorSearch }
// dataSrc: 'data'
},
*/
"ajaxSource": "/Color/Fetch",
//fnServerData method used to inject the parameters into the AJAX call sent to the server-side
"fnServerData": function (sSource, aoData, fnCallback) {
aoData.push({ "name": "color", "value": "Blue" }); // Add some extra data to the sender
$.getJSON(sSource, aoData, function (json) {
/* Do whatever additional processing you want on the callback, then tell DataTables */
fnCallback(json);
});
},
"columns": [
{ "data": "Active" },
{ "data": "Company_Id" },
{ "data": "Id" },
{ "data": "IsActive" },
{ "data": "Name" }
]
});
Here is the information about my development environment:
Microsoft Visual Studio Professional 2013
.NET Framework 4.0
jquery.min.js 1.11.3
jquery-ui.min.js 1.11.2
jQuery DataTables 1.10.7
Newtonsoft.Json.7.0.1
We implemented the tables on our website using jQuery DataTables that involved Server-Side Pagination. In other words, the application will only retrieve data from the database as the user clicks on the Page numbers or Page arrow keys at the bottom of the table.
$('#GameMatchRecordsLogTable').DataTable({
"aoColumns": [
{ "sTitle": "MatchId" },
{ "sTitle": "OrganizerUserID" }, {
"sTitle": "Team1", "bSortable":
true }, { "sTitle": "Team2",
"bSortable": true },
{ "sTitle": "DATE", "sType":
"datetime-us-asc", "bSortable":
true },
],
"bAutoWidth":false,
"fnRowCallback": function (nRow, aData,
iDisplayIndex) {
$(nRow).addClass("gradeX");
},
"iDisplayLength": 10,
"sDom": '<"clear">frtip',
"bProcessing": true,
"bServerSide": true,
"bLengthChange": false,
"bPaginate": true,
"bDestroy": true,
"bSort": true,
"aaSorting": [],
"bInfo": true,
"bFilter": false,
"sAjaxSource":
'GameMatchesList.aspx/SearchBasedOnMultipleCriteriaForGameMatches',
"bJQueryUI": true,
"bDeferRender": true,
"fnServerParams": function (aoData) {
aoData.push(
{ "name": "sortColumnArg",
"value": sortColumnArg }
, { "name": "isDescendingArg",
"value": isDescendingArg }
, { "name": "startDateArg",
"value": startDateArg }
, { "name": "endDateArg", "value":
endDateArg }
, { "name": "OwnersNameArg",
"value": OwnersNameArg }
, { "name":
"searchDrpDutyCycleArg", "value":
searchDrpDutyCycleArg }
, { "name":
"searchDrpSignedStateArg", "value":
searchDrpSignedStateArg }
);
},
"fnServerData": function (sSource, aoData,
fnCallback) {
$.ajax({
"dataType": 'json',
"contentType": "application/json;
charset=utf-8",
"type": "GET",
"url": sSource,
"data": aoData,
"success":
function (msg) {
var obj =
jQuery.parseJSON(msg.d);
fnCallback(obj);
},
beforeSend: function () {
$('.loader').show()
},
complete: function () {
$('.loader').hide()
}
});
}
});
The back-end C# code will resemble something like the following:
[WebMethod]
[ScriptMethod(UseHttpGet = true)]
[WebInvoke(ResponseFormat = WebMessageFormat.Json, BodyStyle =
WebMessageBodyStyle.Bare, Method = "GET")]
public static string
SearchBasedOnMultipleCriteriaForGameMatches()
{
return null;
}
We also need Server-side based sorting for the title headers of the jquery DataTable.
To elaborate, we want user to be able to click on the title Header of the DATE column which would in turn invoke AJAX method which in turn invokes a Server-side C# to get all the Data based on a particular order of the Date , therefore, if user toggles then it would go back and forth between descending and ascending of Date ).
Could someone please explain how I could implementing the aforementioned requirement?
I'm having problem with jQuery DataTables date range filtering. I'm getting (sSearch_0 = undefined~undefined) value with Bootstrap Datepicker. When I put a null value on first column instead of type: "date-range", the 3rd column filter is working fine.
(function ($) {
$(document).ready(function () {
// Implements the dataTables plugin on the HTML table
var oTable = $('#transactionHistoryDataTable').dataTable({
"bJQueryUI": true,
"sPaginationType": "full_numbers",
"bServerSide": true,
"sAjaxSource": "api/Sitecore/Account/DataProviderAction",
"bProcessing": true,
"aoColumns": [
{ "sName": "Date", "bSortable": false },
{ "sName": "Name", "bSortable": false },
{ "sName": "Bracket", "bSortable": false },
{ "sName": "Activity", "bSortable": false },
],
"sDom": '<"top">tip',
"oLanguage": {
"sEmptyTable": "Your custom message for empty table"
}
}).columnFilter({
"aoColumns": [
{ type: "date-range" },
null,
{ type: "select"},
null,
]
});
});
})(jQuery);
UPDATE
I changed my code into server side filtering like this
"fnServerParams": function (aoData) {
aoData.push({ "name": "activityParam", "value": $('#activityList').val() });
aoData.push({ "name": "dateFrom", "value": $('#dateFrom').val() });
aoData.push({ "name": "dateTo", "value": $('#dateTo').val() });
}
The workaround that I've come up with works with jquery ui the problem is I can't use Jquery UI is there any other workaround?