Feed ajax datatable with json from Asp.net MVC Action method - ajax

I am using Ajax Datatable, I want to feed the table with Json data, which i am returning from MVC Action method. This is what i have tried so far,
My Controller action method
public ActionResult Index()
{
_dbcontext = new dbContext();
List<Employee> employees = new List<Employee>();
var query = (from e in _dbcontext.Employees select new { e.FirstName, e.LastName, e.Username, e.Password }).ToList();
return Json(query,JsonRequestBehavior.AllowGet);
}
And here is my Javascript on Index page
</script>
$(document).ready(function () {
$('#example').dataTable({
"processing": true,
"serverSide": true,
"ajax": {
"url": "Home/Index",
"dataType": "jsonp"
}
});
});
</script>
But on page load only the plain Json data can be seen and no data table, I think It is not even rendering the Html on the index page and hence neither Datatable as I can not see anything in chrome debugger.
Also, Html and script referencing is all Ok as I can see the results when I feed the datatable from a .txt file having array of data.
I don't know what is the right way to do that, If somebody has the solution for that, then please help, Thanks.

I think what you need to do is simply the following
</script>
$(document).ready(function () {
$('#example').dataTable({
"ajax": "/Home/Index",
"columns": [
{ "data": "FirstName" },
{ "data": "LastName" },
{ "data": "Username" },
{ "data": "Password" },
]
});
});
</script>
No need for the processing and serverside and they are used when you have large data and would like to have paging and sorting done on the server side which is not the case in your code

One possible way is to define your "regular" table markup in a razor view/partial/ view - id your table, ie, id="DataTables-Employee". Your controller code looks just fine but with an ActionResult return a View with the model data. This let you control the data by using razor syntax in your view, which I have found much easier than complex JSON results. (Also, I like to use AutoMapper to project my model data to - give it a try!)
Note: this is only one of several ways to do this. Server-side processing helps when working with huge datasets, but give the client-side a try. I use ajax but flatten your model result. More likely than not you will need to define your columns and map them to your JSON. If you want to post your table results, add a form tag. I use ajax for this and serialize my form before sending. I hope this helps!
public ActionResult Index()
{
_dbcontext = new dbContext();
List<Employee> employees = new List<Employee>();
var query = (from e in _dbcontext.Employees
select new {e.FirstName, e.LastName, e.Username, e.Password};
//I would recommend using AutoMapper and project your model to this
return View(query.ToArray());
}
Say you are working with an Index view:
#model dynamic
... //typical HTML table
<table class="display compact table table-striped table-hover dataTables_sizing table-condensed" id="dataTables-Employee">
<thead>
<tr>
<th>First Name</th>
<th>Last Name</th>
<th>User Name</th>
<th class="no-sort">Actions</th>
</tr>
</thead>
#foreach (var emp in Model)
{
<tr>
<td>#emp.FirstName</td>
<td>#emp.LastName</td>
<td>#UserName</td>
<td style="width: 100px;">
<i class="fa fa-search"></i>
#Ajax.ActionLink("View", "Index", new { id = #app.EmployeeId },
new AjaxOptions
{
dateTargetId = "resultSection",
HttpMethod = "GET",
InsertionMode = InsertionMode.Replace
})
</td>
</tr>
}
</table>
//Know make it a DataTable
$('#dataTables-Employee').DataTable({
scrollY: '330px',
scrollCollapse: true,
paging: true,
scrollX: false,
"columnDefs": [{
"orderable": false,
"targets": 2
}, {
className: "dt-center",
"targets": [3]
}],
"aria": {
"sortAscending": ": activate to sort column ascending",
"sortDescending": ": activate to sort column descending"
},
"options": {
"emptyTable": "No records to display..."
}
});​
Example of results with Bootstrap styles:

Related

Ajax load data in datatables and set data on button

everything works fine. The only issue that i cannot fix/find is how to create a button and set the value of data: cvpdf inside a href of a button to open the cv
The cvpdf is the file name of a cv stored in the database.
<table id="dtBasicExample" class="table table-striped custom-table mb-0 datatable " >
<thead>
<tr>
<th>id</th>
<th>name</th>
<th>surname</th>
<th>email</th>
<th>position</th>
<th>CV</th>
</tr>
</thead>
<tbody id="atn-tbody">
</tbody>
</table>
function showInformation(str) {
console.log(str);
$("#dtBasicExample").dataTable().fnDestroy();
$(document).ready(function(){
$("#dtBasicExample").dataTable({
scrollX: true,
"ajax":{
url: "data.php?q="+str ,
dataSrc:"",
},
"columns":[
{"data": "id"},
{"data": "name"},
{"data": "surname"},
{"data": "email"},
{"data": "position"},
{"data": "cvpdf"},
]
});
});
};
Let me help you out with this. you can apply this to any column data
columns: [
{
data: function(row){
return `Click This`
}
}
]
the "row" parameter will return the whole data for the current row, so you can access the object through the "row.your_key".
this is the best practice to make your code simpler.
the complete parameter can be accessed through This Link
Hope it can help!

C# jQuery Ajax Datatables ASP.NET Core 5 MVC

I am attempting to implement ASP.NET Core SignalR. I am looking for assistance. The project is located at: https://github.com/Talsiter/AspNetCore-SignalR-SqlTableDependency
The issue that I am running into is when a datatable is being populated from jQuery AJAX, no data is being populated into the view.
Items model (Item.cs)
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
namespace InAndOut.Models
{
public class Item
{
[Key]
public int Id { get; set; }
public string Borrower { get; set; }
public string Lender { get; set; }
[DisplayName("Item name")]
public string ItemName { get; set; }
}
}
Items view (Index.cshtml)
#model IEnumerable<InAndOut.Models.Item>
<div class="container p-3">
<div class="row">
<div class="col-12">
<div class="card">
<div class="card-header">
<div class="card-body">
<table id="myTable" class="table table-bordered table-striped">
<thead>
<tr>
<th>Id</th>
<th>Item Name</th>
<th>Borrower</th>
<th>Lender</th>
<th>Action</th>
</tr>
</thead>
</table>
</div>
</div>
</div>
</div>
</div>
#section Scripts {
#* These Scrips are Required *#
<script src="~/js/signalr/dist/browser/signalr.js"></script>
#*This one gives me an error of "ItemsHub undefined"*#
#*<script src="~/js/items01.js"></script>*#
#* This gives me an error "DataTable is not a function"
This probably requires the *#
<link href="//cdn.datatables.net/1.10.25/css/jquery.dataTables.min.css" rel="stylesheet" />
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/datatables/1.10.21/js/jquery.dataTables.min.js"></script>
<script src="~/js/items03.js"></script>
}
Items JS file (items03.js):
// This is from:
//https://stackoverflow.com/questions/51764211/jquery-datatable-loading-using-ajax-asp-net-mvc
// Does Not Display any data
function getAllMessages() {
$('#myTable').DataTable({
processing: true,
serverSide: false,
ordering: true,
paging: true,
searching: true,
columns: [
{ title: "Id" },
{ title: "ItemName" },
{ title: "Borrower" },
{ title: "Lender" },
{ title: "View Data" }
],
columns: [
{ data: "Id" },
{ data: "ItemName" },
{ data: "Borrower" },
{ data: "Lender" },
{
data: null,
defaultContent: "<button class='tblview'>View Id</button><button class='tblDelete'>Delete</button>"
}
],
ajax: {
"url": "/Item/GetItems",
"type": "GET",
"dataSrc": ''
},
"columnDefs": [
{
"targets": 0,
"visible": false
}
]
});
}
Item controller (ItemController.cs):
// This was updated from:
// https://stackoverflow.com/questions/51705732/jquery-datatable-ajax-no-data-available-mvc
public IActionResult GetItems()
{
var items = new List<Item>
{
new Item { Id = 1, ItemName = "Computer", Borrower = "Justin", Lender = "Don"},
new Item { Id = 2, ItemName = "Mouse", Borrower = "Mark", Lender = "Susan"},
new Item { Id = 3, ItemName = "Monitor", Borrower = "Mark", Lender = "Joe"},
new Item { Id = 4, ItemName = "Keyboard", Borrower = "Candace", Lender = "Angela"},
new Item { Id = 5, ItemName = "Printer", Borrower = "Mike", Lender = "Watson"},
};
// JsonRequestBehavior requires Microsoft.AspNet.MVC
// I do not want to reference it. I want to use Microsoft.AspNetCore.Mvc
//return Json(items, JsonRequestBehavior.AllowGet);
// I referenced this to mitigate the above issue
// https://stackoverflow.com/questions/38578463/asp-net-core-the-name-jsonrequestbehavior-does-not-exist-in-the-current-cont
//return Json(items);
// Error: Cannot read property 'style' of undefined
// This was another option
//return Json(items, new Newtonsoft.Json.JsonSerializerSettings());
// Error: Cannot read property 'style' of undefined
// This seems to be returning the correct data format
// Now the data just is not being displayed in the view
// My error seems to be in the JavaScript
return Json(new { data = items });
}
After many attempts, this is about the closest that I am able to get. While debugging the site, I do not receive any errors, but the mock data does not appear in the items view.
I am suspecting that my issue is in the Items JS file in the getAllMessages() method. I am just not sure how to fix it.
The naming convention for response in asp.net core is camel case instead of pascal case. Also you need remove "dataSrc": ''.
Change like below:
columns: [
{ data: "id" },
{ data: "itemName" },
{ data: "borrower" },
{ data: "lender" },
{
data: null,
defaultContent: "<button class='tblview'>View Id</button><button class='tblDelete'>Delete</button>"
}
],
ajax: {
"url": "/Item/GetItems",
"type": "GET",
//"dataSrc": ''
},

dataTable not displaying the data

i am trying to load data in datatable using ajax, this is my table definition:
<table id="appointments" class="display" width="100%">
<thead>
<tr>
<th>Activité</th>
<th>Pour le</th>
<th>Heure Début</th>
<th>Heure Fin</th>
<th>Référent</th>
<th>Etat</th>
<th>test</th>
<th>test2</th>
<th>test3</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
and this is the ajax call:
$("#appointments").dataTable({
"searching":false,
"ajax":function(data,callback,settings){
$.ajax({
url:"http://test.azprojet.fr/wsazprojet/api/entreprise/ManageAppointements",
datatype:"json",
type:"get",
data:{
domainName:$("[name='url']").val(),
IdUsager:$('input[name="IdUsager"]').val()
},
success:function(data,html,status){
},
error:function(html,status,error){
console.log("new error have occured")
console.log(error)
}
});}
});
when i apply this code , i get an empty dataTable containing the word "loading" ?
what 's wrong ?
update
it looks like that i missed calling callback(data) inside the success function , however after adding that i get this error :
Cannot read property 'length' of undefined
searching for solution i found that i need to set ajax.dataSrc inside the ajax object , but i didn't know how since i m calling a function here !
the problem is that , datatable accept this format of json data:
{
"data": [
{
"name": "Tiger Nixon",
"position": "System Architect",
"salary": "$320,800",
"start_date": "2011/04/25",
"office": "Edinburgh",
"extn": "5421"
}
]
}
so the solution was to add wrap my data like this :
data={"data":data}

Passing data to controller and changing the view

I have the following scenario:
I have a table with a list of book. Now, when I click on the selected rows, I want to send the book titles to the rental controller so that the controller can then call the appropriate view pass the book titles.
Here's the code for the table view:
<button id="checkoutButton">Checkout</button>
<table id="books" class="table table-bordered table-hover">
<thead>
<tr>
<th>Book</th>
<th>Category</th>
<th>Author</th>
<th>Registration Number</th>
<th>Volume</th>
<th>Number In Stock</th>
<th>Number Available</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
}
#section Scripts{
<script>
$(document).ready(function () {
var titles = [];
var table = $("#books").DataTable({
ajax: {
url: "/api/books",
dataSrc: ""
},
columns: [
{
data: "title"
},
{
data: "categoryId"
},
{
data: "registrationNumber"
},
{
data: "volume"
},
{
data: "numberInStock"
},
{
data: "numberAvailable"
},
{
data: "author"
}
]
});
$('#checkoutButton').click(function () {
var obj = table.rows('.selected').data();
if (obj.length == 0)
console.log("No row selected");
else {
for (var i = 0; i < table.rows('.selected').data().length; i++) {
console.log(table.rows('.selected').data()[i].title);
titles.push(table.rows('.selected').data()[i].title);
}
$.ajax({
url: "/Rental/print",
contentType: 'application/json',
method: "POST",
data: JSON.stringify({ titles })
})
}
});
And here's the controller:
public ActionResult print(Object [] titles)
{
for(var i = 0; i < titles.Length; i++)
{
Debug.WriteLine(titles[i]);
}
return View("New");
}
I haven't passed the title to the view yet because the view is not rendering at all. I have verified that the controller does get the data but it does not navigate to the "New.html". Although, if I manually navigate to this page, it does render. So, I am really not sure what I am doing wrong here.
I will very much appreciate if you can point me to the right direction.
Note: I have not included the js code which selects multiple rows because I wanted to keep the code simple. Let me know if I need to show that too.

Datatables Child Rows Implementation

Recently, I got a requirement for an implementation of adding Child rows in a table. I have gone through the few APIs and found that datatables fits into my requirement. As of now I am implementing this web application in Springs and getting the data from the controller.
That is $resultSet.
Now this dynamic data I have to render in jsp page. Here I got stucked because I am not able to implement with datatable. I have seen the example of http://datatables.net/examples/api/row_details.html and tried removing Ajax data and used c:foreach loop in place it. But i didn't get any luck.
So can you guys please tell me how do I use datatables with the dyncamic data in order to display child rows.
My main concern is:
$(document).ready(function() {
var table = $('#example').DataTable( {
"ajax": "../ajax/data/objects.txt",
"columns": [
{
"className": 'details-control',
"orderable": false,
"data": null,
"defaultContent": ''
},
{ "data": "name" },
{ "data": "position" },
{ "data": "office" },
{ "data": "salary" }
],
"order": [[1, 'asc']]
} );
How do I represent the above block.
I tried with <table id="xx"> <c:foreach loop to iterate>
You can use data option to feed data into DataTables directly instead of using server-side script to return data via Ajax. This initialization option can be useful when creating a table from a JavaScript data source, or from a custom Ajax data get. However the data has to be of type Array.
I'm not familiar with Spring framework but I'm assuming you can produce a string with data in JSON format and output it in your page to assign to table_data_json. I'm using a sample JSON string var table_data_json = '[ /* skipped */ ]';.
/* Formatting function for row details - modify as you need */
function format ( d ) {
// `d` is the original data object for the row
return '<table cellpadding="5" cellspacing="0" border="0" style="padding-left:50px;">'+
'<tr>'+
'<td>Full name:</td>'+
'<td>'+d.name+'</td>'+
'</tr>'+
'<tr>'+
'<td>Extension number:</td>'+
'<td>'+d.extn+'</td>'+
'</tr>'+
'<tr>'+
'<td>Extra info:</td>'+
'<td>And any further details here (images etc)...</td>'+
'</tr>'+
'</table>';
}
$(document).ready(function() {
var table_data_json = '[{"name":"Tiger Nixon","position":"System Architect","salary":"$320,800","start_date":"2011/04/25","office":"Edinburgh","extn":"5421"},{"name":"Garrett Winters","position":"Accountant","salary":"$170,750","start_date":"2011/07/25","office":"Tokyo","extn":"8422"},{"name":"Ashton Cox","position":"Junior Technical Author","salary":"$86,000","start_date":"2009/01/12","office":"San Francisco","extn":"1562"}]';
var table = $('#example').DataTable( {
"data": JSON.parse(table_data_json),
"columns": [
{
"className": 'details-control',
"orderable": false,
"data": null,
"defaultContent": ''
},
{ "data": "name" },
{ "data": "position" },
{ "data": "office" },
{ "data": "salary" }
],
"order": [[1, 'asc']]
} );
// Add event listener for opening and closing details
$('#example tbody').on('click', 'td.details-control', function () {
var tr = $(this).closest('tr');
var row = table.row( tr );
if ( row.child.isShown() ) {
// This row is already open - close it
row.child.hide();
tr.removeClass('shown');
}
else {
// Open this row
row.child( format(row.data()) ).show();
tr.addClass('shown');
}
} );
} );
td.details-control {
background: url('https://raw.githubusercontent.com/DataTables/DataTables/1.10.7/examples/resources/details_open.png') no-repeat center center;
cursor: pointer;
}
tr.shown td.details-control {
background: url('https://raw.githubusercontent.com/DataTables/DataTables/1.10.7/examples/resources/details_close.png') no-repeat center center;
}
<link href="//cdn.datatables.net/1.10.7/css/jquery.dataTables.min.css" rel="stylesheet" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script src="//cdn.datatables.net/1.10.7/js/jquery.dataTables.min.js"></script>
<table id="example" class="display">
<thead>
<tr>
<th></th>
<th>Name</th>
<th>Position</th>
<th>Office</th>
<th>Salary</th>
</tr>
</thead>
<tfoot>
<tr>
<th></th>
<th>Name</th>
<th>Position</th>
<th>Office</th>
<th>Salary</th>
</tr>
</tfoot>
</table>
If I misunderstood your question, please let me know and I will update my answer.

Resources