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" }
]
});
Related
How can I catch search text with a parameter in server side. It's always null when I debug the program. I saw this Request.Form.GetValues("search[value]")[0] but I want to take it as a parameter. Is it possible ?
$('#datatableClients').DataTable({
"processing": true,
"serverSide": true,
"filter": true,
"orderMulti": false,
"ajax": {
"url": "/Custom/Data/GetRows",
"type": "POST",
"datatype": "json"
},
"columns": [
{ "data": "FirstName", "name": "First Name", "autoWidth": true },
{ "data": "LastName", "name": "Last Name", "autoWidth": true }
]
});
public JsonResult GetRows(int draw, int start, int length, string search)
{
// search parameter is null
}
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
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 have a dynamic function to generate table data to JSON which kinda works, now I try to add it to a list in .NET however I can't get this right past few days, anybody knows what I do wrong?
the output is like this:
[{"itemsSerialized":"{\"id\":1,\"name\":\"Medical 1\",\"city\":\"Kiev\",\"instituteTypeId\":0}"},{"itemsSerialized":"{\"id\":2,\"name\":\"Medical 2\",\"city\":\"Kherson\",\"instituteTypeId\":0}"}]
which should be without the "itemsSerialized":", I understand where it comes from, but dont understand why a object declaration suddenly shows up in my JSON string
my C# code:
Object itemsSerialized = "";
foreach (DataRow r in _data.Rows)
{
DynamicClass dynamicClass = new DynamicClass();
dyna.ConvertRowToCustomer(r, out dynamicClass);
DynamicClassList.Add(dynamicClass);
var iSerializer = new System.Web.Script.Serialization.JavaScriptSerializer();
itemsSerialized = JsonConvert.SerializeObject(dynamicClass.Property.properties);
Object itemsSerialized2 = JsonConvert.DeserializeObject(xJSON);
Gridist.Add(new { itemsSerialized });
}
with jQuery I have this to load the data into the jQGrid:
$.ajax({
type: "POST",
contentType: "application/json",
url: "dataServices/objects.asmx/InvokeData",
data: "{ 'q': 'med&1'}",
dataType: 'json',
success: function (result) {
var str = result.d;
alert(result.d);
$("#jqGrid_2")[0].addJSONData(result.d);
}
});
The return I have now as:
{"id":1,"name":"Medical 1","city":"Kiev","instituteTypeId":0},{"id":2,"name":"Medical 2","city":"Kherson","instituteTypeId":0}
UPDATE INTERNAL AJAX VERSION:
mtype: 'POST',
contentType: "application/json",
url: "dataServices/objects.asmx/InvokeData",
ajaxGridOptions: {
contentType: 'application/json; charset=utf-8'
},
postData: JSON.stringify({q: "med&1"}),
loadonce: true,
dataType: 'json',
jsonReader: {
root: function (obj) {
alert(obj.d);
return obj.d;
},
page: "",
total: "",
records: function (obj) {
return obj.d.length;
},
},
gridview: true,
loadError: function (xhr, status, error) {
alert('load error: ' + error);
},
And is being written away in the first column from first and only row....
What I do wrong and how I get the itemsSerialized out
First of all the server response
{
"id": 1,
"name": "Medical 1",
"city": "Kiev",
"instituteTypeId": 0
},
{
"id": 2,
"name": "Medical 2",
"city": "Kherson",
"instituteTypeId": 0
}
is wrong. Correct data should be array of items like
[
{
"id": 1,
"name": "Medical 1",
"city": "Kiev",
"instituteTypeId": 0
},
{
"id": 2,
"name": "Medical 2",
"city": "Kherson",
"instituteTypeId": 0
}
]
Another JSON response which you posted contains two problems. 1) "itemsSerialized":" prefix 2) the value of all items are strings
[
{
"itemsSerialized": "{\"id\":1,\"name\":\"Medical 1\",\"city\":\"Kiev\",\"instituteTypeId\":0}"
},
{
"itemsSerialized": "{\"id\":2,\"name\":\"Medical 2\",\"city\":\"Kherson\",\"instituteTypeId\":0}"
}
]
The reason of the first problem is the usage of
Gridist.Add(new { itemsSerialized });
instead of
Gridist.Add(itemsSerialized);
The reason of the second problem is unneeded usage of JsonConvert.SerializeObject. What you should do is something like
Gridist.Add(dynamicClass.Property.properties);
instead of
itemsSerialized = JsonConvert.SerializeObject(dynamicClass.Property.properties);
Gridist.Add(new { itemsSerialized });
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 + '';
}