Unable to bind jQuery DataTable in AJAX call with JSON data - c#

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

Related

Creating html links inside jQuery Datatable

I am currently trying to change asp.net GridView Control to jQuery DataTable with Ajax. In my project, the home page has a justified image grid as shown below:
Each picture works as a link, when the user clicks on a specific image it will redirect the user to another page based on a product Id.
The jQuery DataTable code works for a regular table that has rows & columns. But I want to create my own table inside that jQuery DataTable in order to get the same image grid + links mentioned above.
My code is like this:
1- In Code behind (Default.aspx.cs) I use a simple web method to retrieve data from Database.
[WebMethod]
public static SalesOrderDetail[] BindDatatable()
{
DataTable dt = new DataTable();
List<PDetail > details = new List<PDetail>();
using (SqlConnection con = new SqlConnection(#"server=Server\SQLEXPRESS;integrated security=true;database=MyDb"))
{
using (SqlCommand cmd = new SqlCommand("SELECT Id, PName,ImgUrl FROM Products ORDER BY Id", con))
{
con.Open();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(dt);
foreach (DataRow dtrow in dt.Rows)
{
PDetail p = new PDetail();
p.Id = Convert.ToInt16(dtrow["Id"].ToString());
p.PName= dtrow["PName"].ToString();
p.ImgUrl = Convert.ToInt16(dtrow["ImgUrl"].ToString());
details.Add(p);
}
}
}
return details.ToArray();
}
2- In (Default.aspx) page , there is one table:
<table class="table table-striped table-bordered table-hover" id="TableId"
cellspacing="0" align="center" width="100%">
</table>
3- The jQuery DataTable code looks like this:
$(document).ready(function ()
{
$('#TableId').DataTable(
{
"language":
{
"processing": "<div class='overlay custom-loader-background'><i class='fa fa-cog fa-spin custom-loader-color'></i></div>"
},
"processing": true,
"serverSide": true,
"ajax":{
url: "Default.aspx/GetData",
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;
return return_data.data;
}
}, success: function (data) {
for (var i = 0; i < data.d.length; i++) {
$("#TableId").append("<tr><td><img src="+data.d[i].ImgUrl+"></td></tr>");
}
}
});
});
By the way, the above code is server side processing (paging).
Can anyone tell me or guide me some instructions?
Thanks
I don't recommend you to use the jQuery DataTable for your requirement. Usually this is used instead of HTML tables due to their user-friendliness in handling data. However this implementation should work fine for you. I will give you a couple of links that might suit you for an image grid too at the bottom.
$('#TableId').DataTable({
"processing": true, // show progress bar while loading
"serverSide": true, // process is done on server side
"pageLength": 12, // page size
"ajax": {
"url": "", // your url here
"type": "POST", // since you need to pass data for the request
"datatype": "json",
"data": function (d) {
d.parameter1 = "some value";
d.parameter2 = "another value";
}
},
"columns": [
{
"data": "ImageName",
"name": "Image_Name",
"className": "className",
"defaultContent": "Image Not Found"
},
{
"data": null,
"className": "class1 class2",
"orderable": false,
"render": function (data, type, row) {
var someUrl = "example.com/api/" + data.someVal;
return '< a href="'+ someUrl +'" id="'+ data.Id +'"><img src="'+ data.imageUrl + '" ></a>;
}
},
]
});
Justified,js
Masonry
I personally haven't used these but worth giving a try :)

jQuery datatable using ajax POST method to send custom object

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

Ensuring that jquery DataTable can sort based on invoking by AJAX a Server-Side C# method

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?

How to use SignalR Datasource with Kendo Grid

In order to make a real-time .NET Web application, I am using SignalR for Kendo grid, which works with read, update, destroy method on the grid.
However, my situation is creating and updating records from other pages, the Kendo Grid just for reading data. I would like to implement SignalR to notify user whenever a new record is added to the database.
Here is my code.
SignalRHub class:
public class SignalRHub : Hub
{
private DbEntities db;
public SignalRHub()
{
db = new DbEntities();
}
public IEnumerable<ViewTicketModel> Read()
{
return db.Post_User.AsEnumerable()
.Select(ticket => new ViewTicketModel
{
Id = ticket.Id,
BuyerName = ticket.Name,
DateCreated = ticket.CreatedOn.ToString("dd/MM/yyyy"),
BuyerPhoneNumber = ticket.Mobile,
Details = ticket.Details,
Location = ticket.Location,
})
.OrderByDescending(x => DateTime.ParseExact(x.DateCreated, "dd/MM/yyyy", null))
.ToList();
}
}
Index.cshtml:
var connection = $.connection;
var hub = connection.signalRHub;
var hubStart = connection.hub.start();
console.log("here");
var signalRDataSource = new kendo.data.DataSource({
type: "signalr",
autoSync: true,
push: function(e) {
var notification = $("#notification").data("kendoNotification");
notification.success(e.type);
},
schema: {
model: {
id: "Id",
fields: {
"Id": { editable: false, type: "Number" },
"BuyerName": { type: "string" },
"DateCreated": { type: "string" },
"BuyerPhone": { type: "string" },
"Details": { type: "string" },
"Location": { type: "string" }
}
}
},
transport: {
signalr: {
promise: hubStart,
hub: hub,
server: {
read: "read",
},
client: {
read: "read",
}
}
},
pageSize: 10,
});
$("#grid").kendoGrid({
height: 700,
filterable: {
extra: false,
},
pageable: true,
sortable: {
mode: "multiple",
allowUnsort: true
},
columns: [
{ field: "Id", title: "Notification Id", width: 100, hidden: true },
{
field: "DateCreated",
title: "Date Created",
width: 150,
filterable: {
ui: "datetimepicker"
}
},
{ field: "Location", title: "Location", width: 150 },
{ field: "BuyerName", title: "Buyer Name", width: 120, hidden: true },
{ field: "BuyerPhoneNumber", title: "Buyer Phone", width: 120, hidden: true },
],
dataSource: signalRDataSource
});
by other pages, you meant different application? If that is the case, this will complicate the issue.
remember kendo grid only comes with 4 default signal actions (create, update, read, destroy). Any other will have to be implemented by you.
here's an example how you can make your "connected" clients do a refresh read.
in your hub:
IHubContext context = GlobalHost.ConnectionManager.GetHubContext<Dashboard>();
context.Clients.All.reload();
in your client html page:
<script type="text/javascript">
var hub = $.connection.dashboard;
hub.client.reload = function () {
updategrid();
};
var hubStart = $.connection.hub.start();
function updategrid()
{
$('#GridName').data('kendoGrid').dataSource.read();
$('#GridName').data('kendoGrid').refresh();
}</script>
This will force all your connected clients to do a refresh.
The perfect scenario would be to the appropriate changes pushed out to the client. This implementation can get tricky, because you don't know what filter/sort/grouping the user has on their side. However, it's achievable. You can have each connected client to send it's filter/grouping/sort back to the server and pull only the appropriate change.

create a link in jquery datatable with id from another column

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

Categories

Resources