jQuery datatable - ASP.NET controller parameter always null - javascript

I have the following JavaScript function...
function loadTable(date: string) {
$('#myDataTable').DataTable({
"bServerSide": false,
"sAjaxSource": "Date/GetValuesFromDate",
"data": date
"bAutoWidth": false,
"bProcessing": true,
"aoColumns": [
{ "sName": "MESSAGE" },
{ "sName": "DATE" },
{ "sName": "STATUS" }
]
"bDestroy":true
});
...
That calls the following controller on my ASP.NET WEb Application...
public class DateController : Controller
{
private RegistrationDbContext _context;
public HomeController(RegistrationDbContext context)
{
_context = context;
}
public ActionResult GetValuesFromDate(string date)
{
// Some code here...
return Json(new
{
aaData = results;
});
}
}
However, the value of the string date is always null. I saw that the loadTable() function does contain the date so I have no clue now how to pass that out to the Controller itself...
I hardcoded the date and everything works wonderfull so the only missing piece here is the binding between the JavaScript function and the Controller...
Any pointers?
Thanks!

Trying wrapping up the data param in {} IE
'data': {'date': date}
OR you could directly append it to your source url I think as a query string since it is a GET...
"sAjaxSource": "Date/GetValuesFromDate?date=" + date

Related

Datables serverSide ajax POST 'error': "int() argument must be a string, a bytes-like object or a number, not 'NoneType'"

now i got some error when i try to get data and display on the datatables which using serverSide.
following to my code below i have get my data by using ajax POST method because i want to send some data that need to use to filter in my database, and this is my code.
Javascript
report_table = $('#report_table').DataTable({
"scrollX": true,
"serverSide":true,
"deferRender": true,
"ajax": {
"url": "load_report_table",
"type": "POST",
"data":{
'region_id': function() { return $('#select_reg').val() },
}
},
});
Python
from datatables import ColumnDT, DataTables
from flask import request
#app.route('/load_report_table', methods=['POST', 'GET'])
def load_report_table():
reg_id = request.form['region_id']
columns = [
ColumnDT(Battery_Log.time),
ColumnDT(Battery.serial_number),
ColumnDT(Battery_Log.usage),
]
query = db.session.query().select_from(Battery, Battery_Log)\
.filter(Battery.reg_id == reg_id, Battery_Log.battery_id == Battery.id)
params = request.args.to_dict()
rowTable = DataTables(params, query, columns)
return rowTable.output_result()
but when i print rowTable.output_result() it got the error like this.
{'draw': '1', 'recordsTotal': '14733', 'recordsFiltered': '14733', 'error': "int() argument must be a string, a bytes-like object or a number, not 'NoneType'"}
For now i guess the error that cause by using POST method because when i have change my code to call only url and not post any data to the route function it work normally, the code is show below.
report_table = $('#report_table').DataTable({
"scrollX": true,
"serverSide":true,
"deferRender": true,
"ajax": "load_report_table"
});
So are there anyway to fix that i can POST my data to my route function and return the data to show on the datatables.

Jquery Datatables adding parameter to request

My problem is that i cannot add a parameter to my request without overwriting the other request parameters.
Example
var table = $('#datatable').DataTable({
"bServerSide": true,
"bProcessing": true,
"ajax": {
"url": "/../",
"data": function ( d ) {
return $.extend( {}, d, {
"iLocked": "this is the only thing i receive"
} );
}
},
........
For refference:
https://datatables.net/reference/option/ajax.data (tried all examples)
The code above nulls all other request parameters that I previously received, like:
sEcho,
sSearch,
iDisplayLength,
iDisplayStart,
iColumns,
iSortingCols
sColumns
I need both those requests and my iLocked property.
I also tried this:
fnServerParams: function (aoData) {
aoData.iLocked = { "name":"iLocked","value":"I don't know where to receive this"};
},
In this case I don't know where to receive this parameter.
Receiving parameters: I receive my parameters in two ways:
Controller parameters: public ActionResult AjaxHandler(TableParams
param,string iLocked)
Request: var customParam= Request.Params.Get("iLocked");*
My basic setup looks like this:
https://www.codeproject.com/Articles/155422/jQuery-DataTables-and-ASP-NET-MVC-Integration-Part#Implementation
My jQueryDataTableParamModel also has the iLocked property.
Question
How do I receive both my new parameter without nulling the previous parameters?
Answer
"sAjaxSource": "/../",
"fnServerParams": function (aoData) {
aoData.push( { "name": "iLocked", "value": "my_value" } );
}
Credit: Sending data to the server with fnServerParams and aoData for jquery DataTable does not work in MVC4
Patrick

Data Tables get JSON from API without setting "aaData"

I am using Data Tables and I get my data like it is shown in example
$('.data-table').dataTable({
"bProcessing": true,
"sAjaxSource": "/api/item/list",
"aoColumns": [
{ "mData": "Title" },
{ "mData": "Price" }
]
});
However there is a problem, I need to take all my objects and wrap them in aaData for this to work like so
[HttpGet]
public dynamic List()
{
var items = _db.Items.OrderBy(x => x.ID);
var a = new {
aaData = items
};
return a;
}
And this is bad for obvious reason that I need to modify my back-end for this instead of returning plain-old JSON. I've tried setting aaData instead of sAjaxSource but got errors and it didn't worked. Any ideas on how can I fix this?
Instead of the property aaData, you can tell DataTables to use another property name with the sAjaxDataProp parameter. For example:
// Get data from { "data": { "inner": [...] } }
$(document).ready( function() {
var oTable = $('#example').dataTable( {
"sAjaxSource": "sources/data.txt",
"sAjaxDataProp": "data.inner"
} );
} );

ExtJS: return total rows/records in json store

I have a json store that returns values in json format. Now I need to get the number of rows/records in the json string but when I use store.getCount() function it returns 0, but the combobox is populated with rows, and when I use store.length I get undefined, probably because its not an array anymore, its returning from store, which is calling php script. Anyways, whats the best approach for this problem?
Try this out:
var myStore = Ext.extend(Ext.data.JsonStore, {
... config...,
count : 0,
listeners : {
load : function(){
this.count = this.getCount();
}
}
Ext.reg('myStore', myStore);
and then use inside panels:
items : [{
xtype : 'myStore',
id : 'myStoreId'
}]
Whenever you need to get the count then you can simply do this:
Ext.getCmp('myStoreId').count
Your Json response from server, can be something like this...
{
"total": 9999,
"success": true,
"users": [
{
"id": 1,
"name": "Foo",
"email": "foo#bar.com"
}
]
}
Then you can use reader: {
type : 'json',
root : 'users',
totalProperty : 'total',
successProperty: 'success'
} in your store object.
As from docs if your data source provided you can call getTotalCount to get dataset size.
If you use ajax proxy for the store, smth like
proxy : {
type : 'ajax',
url : 'YOUR URL',
reader : {
type : 'json',
root : 'NAME OF YOUR ROOT ELEMENT',
totalProperty : 'NAME OF YOUR TOTAL PROPERTY' // requiered for paging
}
}
and then load your store like
store.load();
There will be sent Ajax asynchronous request, so you should check count in callback like this
store.load({
callback : function(records, operation, success) {
console.log(this.getCount()); // count considering paging
console.log(this.getTotalCount()); // total size
// or even
console.log(records.length); // number of returned records = getCount()
}
});

Is it possible to mark a store field as readonly in ExtJS?

In ExtJS, I have a JsonStore configured like this:
var store = new Ext.data.JsonStore({
// basic properties
restful: true,
autoSave: true,
// json writer
writer: new Ext.data.JsonWriter({
encode: false,
writeAllFields: true
}),
// field config
fields: [
'id',
'name',
{ name: 'timestamp', type: 'date', dateFormat: 'c' }
]
});
The timestamp property should be set by the server, and the client should only read it. However, if I try to add or update a record using the JsonStore:
// add a record
var record = new store.recordType({ name: 'New record' });
store.insert(0, record);
// update a record
var record = store.getAt(0);
record.set('name', 'Modified record');
The JSON that's being sent over to the server looks like this:
{
"id": 5,
"name": "Modified record",
"timestamp": "01-06-2001T15:23:14"
}
I'd like it to stop sending over the timestamp property, since it's supposed to be read-only. Is there any way of configuring either the store or the record in order to get this behavior?
Since Ext4 you may use
persist: false
in the Model field description
Ext.namespace('Ext.ux');
/**
* Extension of the JsonWriter that doesn't send fields having the config option
* write set to false
* #author Friedrich Röhrs
* #verison 1.0
*
*/
Ext.ux.AdvJsonWriter = function (config) {
Ext.ux.AdvJsonWriter.superclass.constructor.call(this, config);
};
Ext.extend(Ext.ux.AdvJsonWriter, Ext.data.JsonWriter, /** #lends Ext.ux.AdvJsonWriter */{
toHash: function(rec, options) {
var map = rec.fields.map,
data = {},
raw = (this.writeAllFields === false && rec.phantom === false) ? rec.getChanges() : rec.data,
m;
Ext.iterate(raw, function(prop, value){
if((m = map[prop])){
if (m.write !== false)
data[m.mapping ? m.mapping : m.name] = value;
}
});
// we don't want to write Ext auto-generated id to hash. Careful not to remove it on Models not having auto-increment pk though.
// We can tell its not auto-increment if the user defined a DataReader field for it *and* that field's value is non-empty.
// we could also do a RegExp here for the Ext.data.Record AUTO_ID prefix.
if (rec.phantom) {
if (rec.fields.containsKey(this.meta.idProperty) && Ext.isEmpty(rec.data[this.meta.idProperty])) {
delete data[this.meta.idProperty];
}
} else {
data[this.meta.idProperty] = rec.id;
}
return data;
}
});
then
var store = new Ext.data.JsonStore({
// basic properties
restful: true,
autoSave: true,
// json writer
writer: new Ext.ux.AdvJsonWriter({
encode: false,
writeAllFields: true
}),
// field config
fields: [
'id',
'name',
{ name: 'timestamp', type: 'date', dateFormat: 'c', write: false }
]
});
the timestamp field will never be send to server.
If you set {disabled: true} on the timestamp field, it shouldn't be submitted to server
You can also set the default value to whatever you want on the timestamp field. You have configured your JsonWriter to go ahead and write to all fields. If you set the default value to '' or NULL you might be able to get the desired behavior you want.
You could try intercepting the call to the writer and just remove the timestamp at that time:
var writer = new Ext.data.JsonWriter({
encode: false,
writeAllFields: true
});
Ext.intercept(writer, 'render', function(params, baseParams, data) {
delete data.timestamp;
});
var store = new Ext.data.JsonStore({
...
writer: writer,
...
Does writeAllFields have to be true? It defaults to false which wouldn't send the timestamp property if you didn't update it.
Alternatively, you could override the toHash function on the JsonWriter. At the moment it has this comment:
TODO Implement excludes/only configuration with 2nd param
You could add your own implementation of that.

Categories