There is a good example on how to use JQuery Datatables with Core MVC at Using jQuery DataTables Grid With ASP.NET CORE MVC
I download the sample project, made some modifications and it works perfectly.
However, I'm getting an error when I try to integrate this into my project.
DataTables warning: table id=example - Requested unknown parameter 'IdStudent' for row 0, column 0. For more information about this error, please see http://datatables.net/tn/4
After I click ok on the error, the table generates with the correct number of rows, but with no data:
This is my class:
public class GridStudent
{
[Key]
public int IdStudent { get; set; }
public string Name { get; set; }
public string LastName { get; set; }
}
The HTML and JavaScript:
<div class="container">
<br />
<div style="width:90%; margin:0 auto;">
<table id="example" class="table table-striped table-bordered dt-responsive nowrap" width="100%" cellspacing="0">
<thead>
<tr>
<th>IdStudent</th>
<th>Name</th>
<th>LastName</th>
<th>Edit</th>
<th>Delete</th>
</tr>
</thead>
</table>
</div>
</div>
<script>
$(document).ready(function ()
{
$("#example").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": "/StudentGrid/LoadData",
"type": "POST",
"datatype": "json"
},
"columnDefs":
[
{
"targets": [0],
"visible": false,
"searchable": false,
}
],
"columns": [
{ "data": "IdStudent", "name": "IdStudent", "autoWidth": true },
{ "data": "Name", "name": "Name", "autoWidth": true },
{ "data": "LastName", "name": "LastName", "autoWidth": true },
{
"render": function (data, type, full, meta)
{ return '<a class="btn btn-info" href="/StudentGrid/Edit/' + full.IdStudent + '">Edit</a>'; }
}
,
{
data: null, render: function (data, type, row)
{
return "<a href='#' class='btn btn-danger' onclick=DeleteData('" + row.IdStudent + "'); >Delete</a>";
}
},
]
});
});
function DeleteData(CustomerID)
{
if (confirm("Are you sure you want to delete ...?"))
{
Delete(CustomerID);
}
else
{
return false;
}
}
function Delete(CustomerID)
{
var url = '#Url.Content("~/")' + "StudentGrid/Delete";
$.post(url, { ID: CustomerID }, function (data)
{
if (data)
{
oTable = $('#example').DataTable();
oTable.draw();
}
else
{
alert("Something Went Wrong!");
}
});
}
</script>
This is the line of code, from the controller, than returns the data:
return await Task.Run(() => Json(new { draw = draw, recordsFiltered = recordsTotal, recordsTotal = recordsTotal, data = data }));
As you can see from the image, the controller is returning the data correctly, but for some reason DataTables can't read it.
I cross check with the sample a thousand times and I can't see a difference on the format of the data being return.
Any suggestions?
This is most likely due to the casing of the serialized JSON. Your data properties in the column definitions within your JavaScript expect Pascal casing. At present, I expect your are serializing JSON as lower camel case rather than Pascal case (e.g. idStudent instead of IdStudent).
To serialize JSON as Pascal case, make sure you have the following in the ConfigureServices method in your Startup class:
services
.AddMvc()
.AddJsonOptions(options =>
{
options.SerializerSettings.ContractResolver
= new Newtonsoft.Json.Serialization.DefaultContractResolver();
});
Related
I'm creating a list user table on fw laravel by using datatable and axios (not use vuejs), i don't use datatable's pagination but laravel's one because datatables take a lot of time to respond upon retrieving a million records, I can't find a way to use serverside feature cause axios replace ajax feature in severside. The issue began from this:
I'm successful to use laravel's pagination with js but as it comes to 10 or more page, the pagination not update and change the positive upon i click number page, i only can change a page from 1 to 10, here is my pagination code:
display pagination
<div id="pagination">
{!! $axios->links() !!}
</div>
and here is js code
$(document).on('click', '.pagination a',function(e) {
e.preventDefault();
$('li').removeClass('active');
$(this).parent().addClass('active');
let pg = $(this).attr('href')
reloadData(pg)
window.history.pushState("", "",pg)
})
reloadData function:
function reloadData(value){
axios.get(url+'/data'+ value).then(handleResponse)
.catch(function (error) {
console.log(error);
})
function handleResponse(response) {
data = response.data.data;
$('#dataid').DataTable().clear().destroy()
$('#dataid').DataTable({
paging : false,
severSide: true,
processing: true,
deferRender: true,
order: [],
retrieve: true,
pagingType: 'full_numbers',
dom: 'lBfrtip',
columnDefs: [{
"defaultContent": "-",
"targets": "_all"
}],
data: data,
columns: [
{ data: 'name' },
{ data: 'email' },
{ data: 'phone' },
{ data: '' },
{ data: 'created_at' },
{ data: function(data){
return '<td class="pr-0 text-center">'+
'<a id="delete-btn" class="label label-inline label-light-default font-weight-bolder delete-btn" data-id="'+data.id+'" href="javascript:void(0)">Delete'+
'</a>'+ '/'+
'<a id="edit-btn" class="label label-inline label-light-default font-weight-bolder delete-btn" data-id="'+data.id+'" href=" javascript:void(0)">Edit'+
'</a>'+
'</td>'
}}
],
})
}
}
controller :
//display view and pagination
public function index(Request $request)
{
$axios = Apiato::call('User#GetAllUsersAction', [$request]);
$axios->withPath('');
return view('user::Axios.list',compact('axios'));
}
// i retrived the records from this
public function getData(Request $request)
{
//$user = $request->getContent();
//$user = json_decode($user,true);
$axios = Apiato::call('User#GetAllUsersAction', [$request]);
return $axios;
}
i expect something like this upon i click number page : [1],2,3,4,5,...,24,25 --> 1,2,...,[6],7,8,9,...25
I have generated a data table using the Datatables jquery plugin. The table is populated with JSON.
I want to extract cell values when I make a selection to use in a URL but I can't get it to work.
#I'm using django
import json
#my list
users = [[1,26,'John','Smith'],[2,33,'Dave','Johnson'],[1,22,'Aaron','Jones']]
#my json
user_json = json.dumps(users)
<table class="table table-striped- table-bordered table-hover table-checkable" id="user-table">
<thead>
<tr>
<th>Age</th>
<th>Record ID</th>
<th>First Name</th>
<th>Last Name</th>
<th>Actions</th>
</tr>
</thead>
</table>
<script type="text/javascript">
var userData = {{user_json|safe}};
</script>
var SourceHtml = function() {
var dataJSONArray = userData;
var initTable1 = function() {
var table = $('#user-table');
// begin table
table.DataTable({
responsive: true,
data: dataJSONArray,
columnDefs: [
{
targets: -1,
title: 'Actions',
orderable: false,
render: function(data, type, full, meta) {
//this is where I need help. I need for each a-tag to link to a django url pattern such as href="{% url 'users:select-user' id=id_value %}"
return '<i class="la la-edit"></i>';
},
},
],
});
};
return {
//main function to initiate the module
init: function() {
initTable1();
}
};
}();
jQuery(document).ready(function() {
SourceHtml.init();
});
I need a href link to a django url pattern such as href="{% url 'users:select-user' id=id_value %}" in each a tag. however, I can't get the values from the cells.
Datatables columns.render option can be used to access full data source of current row.
By using columns.render as function type, we can use third (3)
parameter to access another column index form same row of data
source.
var userData = [[1,26,'John','Smith'],[2,33,'Dave','Johnson'],[1,22,'Aaron','Jones']];
$('#example').dataTable( {
"columnDefs": [ {
"targets": -1,
"data": null,
"title": 'Actions',
"render": function ( data, type, row, meta ) {
return 'Download';
}
} ]
} );
I have a simple view page, trying to render jquery datable for my view in MVC4.
My view [Admin.cshtml]
<div style="width:90%; margin:0 auto;">
<table id="myTable">
<thead>
<tr>
<th>Practice Name</th>
<th>Practice Address</th>
<th>Practice Email</th>
<th>Practice Telephone</th>
<th>Created Date</th>
</tr>
</thead>
</table>
</div>
and my reference to css and js for jquery datatables are underneath the section:
<link type="text/css" href="//cdn.datatables.net/1.10.9/css/jQuery.dataTables.min.css" rel="stylesheet"/>
#section Scripts{
<script type="text/javascript" src="//cdn.datatables.net/1.10.9/js/jQuery.dataTables.min.js"></script>
<script>
$(document).ready(function () {
$('#myTable').dataTable({
"ajax": {
"url": "/Home/Admin",
"type": "GET",
"datatype": "json"
},
"columns": [
{ "data": "Practice_Name", "autowidth": true },
{ "data": "Practice_Address", "autowidth": true },
{ "data": "Practice_Email", "autowidth": true },
{ "data": "Practice_Telephone", "autowidth": true },
{ "data": "Created_Date", "autowidth": true }
]
});
});
</script>
}
and in my Controller, i have a simple GET section:
public ActionResult Admin()
{
var data = db.Practices.ToList();
return Json(new { data = data }, JsonRequestBehavior.AllowGet);
}
But, when i run this application, i am getting my resultset like this
Where am i going wrong ?
Change your controller method name:
public ActionResult Admin() to public ActionResult GetAdminData()
Create another action method:
[Authorize]
public ActionResult Admin () => View();
Modify your JavaScript code:
"url": "/Home/Admin" to "url": "/Home/GetAdminData"
And update CDN links because they are too old:
https://cdn.datatables.net/1.10.19/css/jquery.dataTables.min.css
https://cdn.datatables.net/1.10.19/js/jquery.dataTables.min.js
Why is all of this needed?
When you navigate to /Home/Admin your return View (the Admin.cshtml)
Your view contains some custom JavaScript logic which will try to fetch a list of items from the database (your GetAdminData method)
GetAdminData returns JSON which can be used by DataTables in order to show your desired content on the page.
I am calling an Action (Edit or Delete) on a Controller from an <a> tag generated in Javascript. I am trying to pass a parameter ('abc123') but the parameter is null when it gets to the controller.
I have tried various ways to create the <a> tag but I always end up with a null parameter showing up at the controller.
End result of generated <a> tags:
<a class="popup" href="./SiteAdmin/Edit?=abc123">Edit</a>
<a class="popup" href="./SiteAdmin/Delete/abc123">Delete</a>
HTML:
<div style="width: 90%; margin: 0, auto" class="tableContainer">
<a class="popup" href="./SiteAdmin/Save/0" style="margin-bottom:20px; margin-top: 20px;">Add New User</a>
<table id="tblUserAdmin" class="table admin-table">
<thead>
<tr>
<th>USERID</th>
<th>Name</th>
<th>role_id</th>
<th>Role</th>
<th>Modified By</th>
<th>Modified Date</th>
<th>Edit</th>
<th>Delete</th>
</tr>
</thead>
</table>
</div>
Javascript:
var oTable = $('#tblUserAdmin').DataTable({
"ajax": {
"url": './SiteAdmin/getUsers',
"type": "GET",
"datatype": "json"
},
"columns": [
{ "data": "userid" },
{ "data": "name" },
{ "data": "role_id" },
{ "data": "role_nm" },
{ "data": "modifiedBy" },
{ "data": "modifiedDT" },
{
"data": "userid", "render": function (data) {
return '<a class="popup" href= "./SiteAdmin/Edit?=' + data + '">Edit</a>';
}
},
{
"data": "userid", "render": function (data) {
return '<a class="popup" href= "./SiteAdmin/Delete/' + data + '">Delete</a>';
}
}
Controller:
public class SiteAdminController : Controller
{
private Customer db = new Customer();
public ActionResult Index()
{
return View("~/Views/SiteAdmin/Index.cshtml");
}
[HttpGet]
public ActionResult Edit(string id)
{
// put a break point here to see id was null
var usr = new sec_users();
usr = db.sec_users.Where(a => a.userid == id).FirstOrDefault();
return View(usr);
}
}
I am new at JSon and have been searching all over the internet but can't find out where is the error. Can you help me, please? The controller returns the object but nothing is displayed, and it comes out an error saying "Cannot read property 'length' of undefined"`.
This is my main template file:
<link href="~/Content/bootstrap.min.css" rel="stylesheet" />
<link href="~/Content/bootstrap-theme.min.css" rel="stylesheet" />
<script src="~/scripts/jquery-1.9.1.js"></script>
<script src="~/scripts/bootstrap.min.js"></script>
<!-- Data table -->
<link rel="stylesheet" href="https://cdn.datatables.net/1.10.10/css/dataTables.bootstrap.min.css " />
<script src="https://cdn.datatables.net/1.10.10/js/jquery.dataTables.min.js" type="text/javascript"></script>
<script src="https://cdn.datatables.net/1.10.10/js/dataTables.bootstrap.min.js" type="text/javascript"></script>
This is my table:
<table class="table table-bordered" id="tabela">
<thead>
<tr>
<th>Nome</th>
<th>Quantidade</th>
<th>Preco</th>
<th></th>
</tr>
</thead>
</table>
This is my JSon:
$('#tabela').DataTable({
"columnDefs": [
{ "width": "5%", "targets": [0] }, {
"className": "text-center custom-middle-align",
"targets": [0, 1, 2, 3]
},
],
"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": "/produto/BuscarTodos",
"type": "POST",
"dataType": "JSON"
},
"columns": [{
"data": "Nome"
}, {
"data": "Preco"
}, {
"data": "Quantidade"
}, {
"data": "IdProduto"
}, ]
});
This is my controller:
public JsonResult BuscarTodos()
{
try
{
string dados = "";
// Initialization.
string search = Request.Form.GetValues("search[value]")[0];
string draw = Request.Form.GetValues("draw")[0];
string order = Request.Form.GetValues("order[0][column]")[0];
string orderDir = Request.Form.GetValues("order[0][dir]")[0];
int startRec = Convert.ToInt32(Request.Form.GetValues("start")[0]);
int pageSize = Convert.ToInt32(Request.Form.GetValues("length")[0]);
ProdutoConexao con = new ProdutoConexao();
List<Produto> lista = new List<Produto>();
lista = con.FindAll();
// Total record count.
int totalRecords = lista.Count;
if (!string.IsNullOrEmpty(search) && !string.IsNullOrWhiteSpace(search))
{
// Apply search
lista = lista.Where(p => p.Nome.ToLower().Contains(search.ToLower())).ToList();
}
// Sorting.
lista = this.SortByColumnWithOrder(order, orderDir, lista);
// Filter record count.
int recFilter = lista.Count;
// Apply pagination.
lista = lista.Skip(startRec).Take(pageSize).ToList();
// Loading drop down lists.
var result = this.Json(new
{
draw = Convert.ToInt32(draw),
recordsTotal = totalRecords,
recordsFiltered = recFilter,
data = lista
}, JsonRequestBehavior.AllowGet);
return Json(result);
}
catch (Exception ex)
{
return Json(ex);
}
}
private List<Produto> SortByColumnWithOrder(string order, string orderDir, List<Produto> data)
{
// Initialization.
List<Produto> lista = new List<Produto>();
try
{
// Sorting
switch (order)
{
case "0":
// Setting.
lista = orderDir.Equals("DESC", StringComparison.CurrentCultureIgnoreCase) ? data.OrderByDescending(p => p.Nome).ToList() : data.OrderBy(p => p.Nome).ToList();
break;
}
catch (Exception ex)
{
// info.
Console.Write(ex);
}
// info.
return lista;
}
Just to check that your datatable setup is up and correct I will suggest to create an empty table (no controller) just to make sure that you have everything setup correctly. If that works I'll add your controller and dynamic data.
Datatables REQUIRE a specific HTML table format if it can't find it then you'll get that error.
The simplest table you can check with is the following:
<table>
<thead>
<tr>
<th>header 1</th>
</tr>
</thead>
<tbody>
<tr>
<td>Content 1</td>
</tr>
</tbody>
<tfoot>
<tr>
<td>Footer 1</td>
</tr>
</tfoot>
The footer is optional, everything else is required.
EDIT 1:
Take a look at the similar example they posted