DataTables Error : “Requested unknown parameter” - asp.net-mvc

var headers = [{ "mDataProp": "Agents" },{ "mDataProp": "Buyer" },{ "mDataProp": "Date" }];
$(document).ready(function () {
$('#data-table').dataTable({
"bFilter": false,
"bLengthChange": false,
"iDisplayLength": 25,
"bJQueryUI": true,
"bServerSide": true,
"bProcessing": true,
"sPaginationType": "full_numbers",
"aoColumns": headers,
"sAjaxSource": '/report/TestPaging',
});
});
If I remove the aoColumns from my code the datatable is generated normally, but when I add aoColumns I get :
DataTables warning (table id = 'data-table'): Requested unknown parameter 'Agents' from the data source for row 0
HTML:
<table id="data-table">
<thead>
<tr>
<th>tmp</th>
<th>tmp</th>
<th>tmp</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
How can I configure header names? I need them for my sorting.
Do they have to be same as in "th" tags?
Json response from my controller is ok because it renders fine when I remove aoColumns
I have string[][](var data) with 3 strings in each line and return it as
Json(new{
sEcho = param.sEcho,
iTotalRecords = visitRepository.Query.Count(),
iTotalDisplayRecords = visitRepository.Query.Count(),
aaData = data
}, JsonRequestBehavior.AllowGet);

The error you are experiencing is caused by a mismatch between the contents of the JSON and your aoColumns definition. The names you are targeting in aoColumns must be exactly the same as those in the JSON, and the length of each object in the JSON must be equal to the number of columns in the original HTML table. See the docs for clarification. In your case, the JSON should look like this :
[{
"Agents": "tM4Ga0zX",
"Buyer": "ZKwMEiIa",
"Date": "K3lS2yn9"
},
...]
...And your JSON doesnt follow that scheme. If you are not using aoColumns, then the data is inserted by index, not by name - and that is why it is working for you without it.
You configure header names (titles) by the sTitle property :
aoColumns: [
{ mDataProp: "Agents", sTitle : "Agents" },
{ mDataProp: "Buyer", sTitle : "Buyer" },
{ mDataProp: "Date", sTitle : "Date" }
]
see this demonstration based on your question -> http://jsfiddle.net/kLR7G/

Related

Error while trying to load server-side data into razor page using datatables

My table code in view is:
<table class="table table-bordered table-hover table-striped table-content" id="table3">
<thead>
<tr>
<th>messageId</th>
<th>messageText</th>
<th>messageDate</th>
<th>receiverUserId</th>
<th>isSeen</th>
<th>senderId</th>
<th>dateSeen</th>
<th>user</th>
</tr>
</thead>
jQuery code:
$('#table3').DataTable( {
"processing": true, // for show progress bar
"serverSide": true, // for process server side
"filter": true, // this is for disable filter (search box)
"orderMulti": false, // for disable multiple column at once
"ajax": {
"url": "/Admin/LoadPmData",
"type": "POST",
"datatype": "json",
"columns": [
{"data":"messageId"},
{"data":"messageText"},
{"data":"messageDate"},
{"data":"receiverUserId"},
{"data":"isSeen"},
{"data":"senderId"},
{"data":"dateSeen"},
{"data":"user"}
]
}
});
The controller:
[HttpPost]
public JsonResult LoadPmData()
{
var pm = _messageRepository.GetAllMessages();
return Json(new { data = JsonSerializer.Serialize(pm) });
}
I have the following error as alert:
DataTables warning: table id=table3 - Requested unknown parameter '1' for row 0. For more information about this error, please see http://datatables.net/tn/4
How can I fix it?
You only need to put a list into Json(),Here is a demo:
controller:
[HttpPost]
public JsonResult LoadPmData()
{
var pm = _messageRepository.GetAllMessages();//make sure the type of pm is List<Message>
return Json(pm);
}
jQuery(try to put columns outside ajax):
<script type="text/javascript" src="https://code.jquery.com/jquery-1.11.3.min.js"></script>
<script type="text/javascript" src="https://cdn.datatables.net/1.10.8/js/jquery.dataTables.min.js"></script>
<script>
$('#table3').DataTable( {
"processing": true, // for show progress bar
"serverSide": true, // for process server side
"filter": true, // this is for disable filter (search box)
"orderMulti": false, // for disable multiple column at once
"ajax": {
"url": "/Admin/LoadPmData",
"dataSrc": ""
},
"columns": [
{"data":"messageId"},
{"data":"messageText"},
{"data":"messageDate"},
{"data":"receiverUserId"},
{"data":"isSeen"},
{"data":"senderId"},
{"data":"dateSeen"},
{"data":"user"}
]
});
</script>
result:

Making a button visible based on number of records in datatable

I am using jquery datatable in asp.net mvc and i want to show a submit button which will be saving the data to the database only if there is atleast one row in the datatable.
I am trying this code, however its not working
<tr id="trbtnSubmit">
<td colspan="9" align="center">
<input type="submit" name="btnSubmit" value="Save"
class="btn btn-edit btn-text" />
</td>
</tr>
<script>
var PopUp, dataTable;
$(document).ready(function () {
dataTable = $("#tblCustomerList").DataTable({
"ajax": {
"url": "/Customer/GetCustomers",
"type": "GET",
"data": "json"
},
"lengthChange": false,
"pageLength": 10,
"columns": [
{ "data": "Number" },
{ "data": "Name" },
{ "data": "fileName" },
{ "data": "mD5Hash" },
{ "data": "dataSizeInGB" },
{
"data": "Id",
"render": function () {
return "<a href='#'><i class='fa fa-eye'></a></i><a href='#' style='margin-left:5px'><i class='fa fa-pencil'></i></a><a href='#' style='margin-left:5px'><i class='fa fa-trash'></a></i>";
},
"orderable": false,
"width": "40px"
},
],
"language": {
"emptyTable": "No Customers , click on <b>New Customer</b> to add Customers"
}
});
var table = $('#tblCustomerList').DataTable();
if (!table.data().any()) {
$('#trbtnSubmit').hide();
} else {
$('#trbtnSubmit').show();
}
});
</script>
Since you didn't specify the version of datatables, I assume it's v1.10.
And there are 2 side notes I want to make before going into your problem:
Difference between .datatable() and .DataTable()
Enable server-side processing
Difference Between .datatable() and .DataTable()
I saw you declared another variable, var table, at the bottom of your sample code to get another instance of DataTables and check if there is any data? You actually don't need to.
.DataTable() returns a DataTables API instance, while .datatable() returns a jQuery object.
So if you intent to make usages on the DataTables APIs after you initialize the table, you can just use the varirable you declared from the beginning, var dataTable since you used .DataTable() way.
Enable Server-side Processing
Server-side processing is enabled by turning on the serverSide option, and configuring the ajax option. You're missing the first one, whose default is false.
So you might need to add serverSide option in your code:
dataTable = $("#tblCustomerList").DataTable({
serverSide: true,
ajax: {
...
},
...
});
Enough said. Now looking at your problem ...
DataTables Callbacks
There are many ways to achieve what you want to do, and I like to use callbacks so that you can configure your DataTables in one place.
There are lots of callbacks you can use, and the one I would use is drawCallback:
dataTable = $("#tblCustomerList").DataTable({
serverSide: true,
...,
language: {
emptyTable: "No Customers , click on <b>New Customer</b> to add Customers"
},
drawCallback: function(settings) {
$('#trbtnSubmit').toggle(settings.aoData.length > 0);
}
});
Hopefully my code is readable enough without any additional explanations :)

Error: cannot call methods on tabulator prior to initialization; attempted to call method 'addRow'

I have a page with a table:
<table id="myTable">
<thead>
<tr>
<th>Description</th>
<th>Qty</th>
<th>Cost</th>
</tr>
</thead>
<tbody>
#foreach (var item in Model)
{
#Html.EditorFor(model => item);
}
</tbody>
</table>
And I then initialise Tabular like so:
$("#myTable").tabulator({
layout: "fitColumns",
addRowPos: "bottom",
columns: [
{ title: "Description", field: "Description", editor: "input" },
{ title: "Qty", field: "Quantity", sorter: "number", editor: "number", editorParams: { min: 0, step: 1, } },
{ title: "Cost", field: "Cost", sorter: "number", editor: "number", editorParams: { min: 0, step: 0.1, }, align: "right", formatterParams: { decimal: '.', thousand: '.', symbol: "R" }, bottomCalc: "sum", bottomCalcFormatter: "money", bottomCalcFormatterParams: { decimal: '.', thousand: '.', symbol: "R" } },
{ formatter: "buttonCross", width: 30, align: "center", cellClick: function (e, cell) { cell.getRow().delete(); } },
],
});
This all works pretty nicely, but I attempted to add:
$("#add-row").click(function () {
$("#myTable").tabulator("addRow", {}, true);
});
clicking on my button to add a new row results in: Error: cannot call methods on tabulator prior to initialization; attempted to call method 'addRow'
I tried to do: var table = $("#myTable").tabulator... with table.addRow({}) but then I get an error saying addRow is not a function.
Is it supposed to work like this?
That message suggests that you havnt created your Tabulator object before you have called the addRow function.
If you are new to Tabulator then i would suggest that you dont use the jQuery wrapper. that was there more for legacy reasons from the old 3.5 version.
In this case you should use the constructor:
var table = new Tabulator("#myTable", {
layout: "fitColumns",
addRowPos: "bottom",
columns: [
{ title: "Description", field: "Description", editor: "input" },
{ title: "Qty", field: "Quantity", sorter: "number", editor: "number", editorParams: { min: 0, step: 1, } },
{ title: "Cost", field: "Cost", sorter: "number", editor: "number", editorParams: { min: 0, step: 0.1, }, align: "right", formatterParams: { decimal: '.', thousand: '.', symbol: "R" }, bottomCalc: "sum", bottomCalcFormatter: "money", bottomCalcFormatterParams: { decimal: '.', thousand: '.', symbol: "R" } },
{ formatter: "buttonCross", width: 30, align: "center", cellClick: function (e, cell) { cell.getRow().delete(); } },
],
});
And then you can add rows like this:
table.addRow({}, true);
You just need to make sure that when you assign it to the table variable it is in a scope where it can be accessed by all functions that need it
I was initialising a Tabulator onto an existing table targetting the <table id="myTable"> element. Although this works great initially, trying other stuff (like in my question) kept on resulting in 'Error: cannot call methods on tabulator prior to initialization'.
I ended up scraping the predefined <table> and went with initialising on <div id="myTable"> and getting the data via ajax.
Now it all works as expected/documented. Dunno if this is a bug/supposed to work like this/my own incompetence, but at least I can move on.

Showing "Processing..." in datatable when data is empty in mvc view

Showing "Processing..." in datatable when data is empty in mvc view. I am confusing that why it is showing "Processing...". If there is empty data then it want to show "No data available in table"
Here is my code
[View Side]
<div class="row">
<div class="col-md-12">
<table id="dataGrid" class="display table table-striped table-bordered dt-responsive nowrap" width="100%" cellspacing="0">
<thead>
<tr>
<th>Id</th>
<th>Document Name</th>
<th>Other Document Name</th>
<th>Image</th>
<th>Action</th>
</tr>
</thead>
</table>
</div>
</div>
<script>
$(document).ready(function () {
var data = {
'customerId': #Model.Id,
}
addAntiForgeryToken(data);
// DataTable
$("#dataGrid").DataTable({
"scrollX": true, // scrolling horizontal
"bSort": false,
"bFilter": false,
"processing": true, // for show progress bar
"serverSide": true, // for process server side
"pageLength": 5,
"lengthMenu": [5, 10, 50, 100, 1000, 10000],
"ajax": {
"url": "/Admin/FreeLancer/list",
"type": "POST",
"datatype": "json",
"data": data,
"success": function (data) {
}
},
"columnDefs":
[{
"targets": [0],
"visible": false,
"searchable": false,
"orderable": false,
}
],
"columns": [
{ "data": "Id", "name": "Id", "autoWidth": true },
{ "data": "DocumentName", "name": "DocumentName", "autoWidth": true },
{ "data": "OtherDocumentName", "name": "otherdocumentname", "autoWidth": true },
{ "data": "UploadID", "name": "UploadID", "autoWidth": true },
{
"render": function (data, type, row) {
//return "<a target='_blank' href='/Download/GetDownload?downloadId=" + row.UploadID + "' class='btn btn-info'>Download </a>" +
//"<a href='#' class='btn btn-danger' onclick=DeleteData('" + row.Id + "');>Delete</a>"; }
return "<a href='#' class='btn btn-danger' onclick=DeleteData('" + row.Id + "');>Delete</a>";
}
},
],
});
});
</script>
[Controller Side]
[HttpPost]
public IActionResult List(int customerId)
{
// getting all data
var dataList = _customerRegister.DocumentList(customerId,
start: Convert.ToInt32(Request.Form["start"]),
pageSize: Request.Form["length"].ToString() != null ? Convert.ToInt32(Request.Form["length"].ToString()) : 0,
sortColumnName: Request.Form["columns[" + Request.Form["order[0][column]"] + "][name]"],
sortColumnDirection: Request.Form["order[0][dir]"]);
var data = dataList.Select(x => new
{
Id = x.Id,
DocumentName = x.DocumentName,
OtherDocumentName = x.OtherDocumentName,
UploadID = x.UploadID,
});
//returning json data
Response.StatusCode = 200;
return Json(new { draw = Request.Form["draw"], recordsfiltered = dataList.TotalCount, recordstotal = dataList.TotalCount, data = data });
}
This is the code, but I dont think so that their is any problem in the code
Have you checked the DataTables dom property?
$("#table_selector").DataTable({
dom: 'r<"datatable-header"fl><"datatable-scroll"t><"datatable-footer"ip>',
processing: true,
serverSide: true
});
Options
The built-in table control elements in DataTables are:
l - length changing input control
f - filtering input
t - The table!
i - Table information summary
p - pagination control
r - processing display element
https://datatables.net/reference/option/dom
I can see that there is no code for displaying the message. If you are using JQuery Data table which i have notice you can use:
oLanguage: {
sEmptyTable: "Message",
sZeroRecords: "Message",
},

Jquery Autocomplete

iam using jquery autocomplete in asp.net project. it's not working. do you have any idea. the code is given below.
<script type="text/javascript">
$(function () {
$('#clientabbrev').val("");
$("#clientstate").autocomplete({
source: "clientstates.aspx",
select: function (event, ui) {
$('#clientstateid').val(ui.item.clientid);
$('#clientstateabbrev').val(ui.item.clientabbrev);
}
});
$("#clientstate_abbrev").autocomplete({
source: "clientstatesabbrev.aspx",
minLength: 2
});
});
</script>
problem is states.aspx returning the data but it is not showing in the jquery autocomplete control.
Your server needs to return a JSON serialized array of objects with properties id, label, and value. E.g. :
[ { "id": "1", "label": "Mike Smith", "value": "Mike Smith" }, { "id": "2", "label": "Bruce Wayne", "value": "Bruce Wayne" }]
Can you confirm with firebug or Fiddler that your server is returning the correct response?
If you're having trouble serializing your data in C#, you can try using JavaScriptSerializer like this:
var result = from u in users
select new {
id = u.Id,
value = u.Name,
label = u.Name
};
JavaScriptSerialier serializer = new JavaScriptSerializer();
var json = serializer.Serialize(result);
// now return json in your response

Resources