How to add edit functionality in datatable with bootstrap and MVC - javascript

I have done following code and now iI want to add edit column in Bootstrap Datatable with server side functionality in MVC and Bootstrap. Finally I want proper CRUD operation, so how can I approach for this?
<script type="text/javascript">
var assetListVM;
$(function () {
assetListVM = {
dt: null,
init: function () {
dt = $('#assets-data-table').DataTable({
"serverSide": true,
"processing": true,
"ajax": {
"url": "#Url.Action("Get","Asset")"
},
"columns": [
{ "title": "ID", "data": "ID", "searchable": true },
{ "title": "Name", "data": "Name", "searchable": true },
{ "title": "City", "data": "City", "searchable": true },
{ "title": "EmpCode", "data": "EmpCode", "searchable": true },
{ "title": "DOJ", "data": "DOJ", "searchable": true },
{ "title": "Address", "data": "Address" },
{ "title": "DOB", "data": "DOB" }
],
"lengthMenu": [[10, 25, 50, 100], [10, 25, 50, 100]],
});
}
}
// initialize the datatables
assetListVM.init();
});
</script>

Related

How to reduce repetition in Javascript code?

I have ASP.NET Code that use JS for datatable for views. And i do some repetiting code because i have 3 tables (in this case) that i have same columns. just the data(json) that different i have got from controller.
Here's the JS Code
<script type="text/javascript">
function parseDate(date) {
if (!date) {
return ""
}
return new Date(parseInt(date.substr(6))).toLocaleString();
}
$(document).ready(function() {
$.ajax({
"url": "#Url.Action("GetAllByUserToday", "Dashboard")",
"type": "GET",
"datatype": "json",
"success": function(res) {
const mapped = res.data.map((dt) => {
return {
...dt,
CreatedDate: parseDate(dt.CreatedDate),
Status: dt.Status ? "Sukses" : "Gagal",
IsUsingTemplate: dt.IsUsingTemplate ? "Ya" : "Tidak"
};
});
$("#getAllToday").DataTable({
"data": mapped,
"dom": 'Bfrtip',
"buttons": ['copy', 'excel'],
"columns": [
{ "data": "Nama" },
{ "data": "NoHP" },
{ "data": "Content" },
{ "data": "Sender" },
{ "data": "IsUsingTemplate" },
{ "data": "Status" },
{ "data": "CreatedDate" }
],
columnDefs: [{ 'targets': 0, type: 'date-euro' }],
order: [0, 'desc'],
});
}
});
$("#getAll_wrapper").addClass("w-100");
});
$(document).ready(function() {
$.ajax({
"url": "#Url.Action("GetAllSentByUserToday", "Dashboard")",
"type": "GET",
"datatype": "json",
"success": function(res) {
const mapped = res.data?.map((dt) => {
return {
...dt,
CreatedDate: parseDate(dt.CreatedDate),
Status: dt.Status ? "Sukses" : "Gagal",
IsUsingTemplate: dt.IsUsingTemplate ? "Ya" : "Tidak"
};
});
$("#getAllSentToday").DataTable({
"data": mapped,
"dom": 'Bfrtip',
"buttons": ['copy', 'excel'],
"columns": [
{ "data": "Nama" },
{ "data": "NoHP" },
{ "data": "Content" },
{ "data": "Sender" },
{ "data": "IsUsingTemplate" },
{ "data": "Status" },
{ "data": "CreatedDate" }
],
columnDefs: [{ 'targets': 0, type: 'date-euro' }],
order: [0, 'desc'],
});
}
});
});
$(document).ready(function() {
$.ajax({
"url": "#Url.Action("GetAllFailedByUserToday", "Dashboard")",
"type": "GET",
"datatype": "json",
"success": function(res) {
const mapped = res.data.map((dt) => {
return {
...dt,
CreatedDate: parseDate(dt.CreatedDate),
Status: dt.Status ? "Sukses" : "Gagal",
IsUsingTemplate: dt.IsUsingTemplate ? "Ya" : "Tidak"
};
});
$("#getAllFailedToday").DataTable({
"data": mapped,
"dom": 'Bfrtip',
"buttons": ['copy', 'excel'],
"columns": [
{ "data": "Nama" },
{ "data": "NoHP" },
{ "data": "Content" },
{ "data": "Sender" },
{ "data": "IsUsingTemplate" },
{ "data": "Status" },
{ "data": "CreatedDate" }
],
columnDefs: [{ 'targets': 0, type: 'date-euro' }],
order: [0, 'desc'],
});
}
});
});
</script>
Can I reduce the repetition for these code. If can, please help me. So I can try to apply for another page that has same issue. Thank you.
Update, suggestion from #Roamer-1888 finally I try this and it works!
function renderTable(action, tableId) {
$.ajax({
"url": action,
"type": "GET",
"datatype": "json",
"success": function(res) {
const mapped = res.data.map((dt) => {
return {
...dt,
CreatedDate: parseDate(dt.CreatedDate),
Status: dt.Status ? "Sukses" : "Gagal",
IsUsingTemplate: dt.IsUsingTemplate ? "Ya" : "Tidak"
};
});
$(tableId).DataTable({
"responsive": true,
"lengthChange": false,
"autoWidth": false,
"data": mapped,
"dom": 'Bfrtip',
"buttons": ['copy', 'excel'],
"columns": [
{ "data": "Nama" },
{ "data": "NoHP" },
{ "data": "Content" },
{ "data": "Sender" },
{ "data": "IsUsingTemplate" },
{ "data": "Status" },
{ "data": "CreatedDate" }
],
columnDefs: [{ 'targets': 0, type: 'date-euro' }],
order: [0, 'desc'],
});
}
});
}
$(document).ready(function() {
renderTable("#Url.Action("GetAllByUser", "Dashboard")", "#getByUser")
renderTable("#Url.Action("GetAllSentByUser", "Dashboard")", "#getSentByUser")
renderTable("#Url.Action("GetAllFailedByUser", "Dashboard")","getFailedByUser")
});

Ordering columns in JQuery DataTable -- when data is fed through Javascript

There are some forum questions similar to what I'm trying to do but I haven't been able to make it work.
We are pulling data into a DataTable through javascript. I'd like to set the data-order using a different column.
However, when I try the column is being interpreted as a string and not integer.
Here is what makes the table:
var securityTable = $('#security-table').DataTable({
"data": securitydata.guards,
"columns": [
{
"className": 'details-control',
"data": null,
"orderable": false,
//creates square for details row
"render": function (d) {
return '<i class="fa fa-plus-square" aria-hidden="true"></span>';
},
"defaultContent": ''
},
// is sorting by "sort" but is seeing numbers as alphebetical not numeric
{ "data": {
_: "date.display",
sort: "date.date_order"
} },
{ "data": "place" },
{ "data": {
_: "shot.display",
sort: "shot.shot_order"
} },
],
"paging": false,
"searching": false
});
This is what the data looks like:
var securitydata = {
"guards": [
{
"date": {
"display": "April 15, 2011",
"date_order": 1
},
"reported": "Yes",
"place": "Chicago, auto parts yard",
"shot": {
"display": "No one hit",
"shot_order": 24
},
"blurb": "A 52-year-old guard at an auto parts lot shot at a vehicle he said was coming toward him. The man inside the vehicle, accused of stealing equipment from the lot, drove away and was not reported injured.",
"link": ""
},
This is what we were using for help
Using the same example, but with sorthing
$(document).ready(function() {
$('#example').DataTable( {
order: [[ 2, "desc" ]],
ajax: "data/orthogonal.txt",
columns: [
{ data: "name" },
{ data: "position" },
{ data: "office" },
{ data: "extn" },
{ data: {
_: "start_date.display",
sort: "start_date.timestamp"
} },
{ data: "salary" }
]
} );
} );
Link to order here

jquery datatable doesn't sort

I have a jquery datatable that is populated by server side ajax. Supposedly, datatables are supposed to be sortable by default without having to add any parameters. Mine isn't. The sort arrows show up in the column headers and clicking on them flips the arrow but nothing gets sorted.
Here's the datatable definition:
$('#appPotTable').DataTable({
"ordering": true,
"processing": true,
"serverSide": true,
"ajax": "/MoneyMachine/screen_analystEst.php",
"columns": [
{ "data": "Symbol", "sortable":true },
{ "data": "CompanyName" },
{ "data": "StockType" },
{ "data": "ExDivDate" },
{ "data": "Dividend" },
{ "data": "DivYield" },
{ "data": "DivFrequency" },
{ "data": "DivPayDate" },
{ "data": "PriceToNav" },
{ "data": "AppreciationPotential" }
]
});
I've tried it with and without the "ordering" and "sortable" parameters but same result. I've also tried various column definition parameters with no joy. Suggestions?
Thanks to Ogreucha for suggesting to turn off server side processing. I did that and now sorting works fine. Here is the new code:
$('#appPotTable').DataTable({
"ajax": "/MoneyMachine/screen_analystEst.php",
"columns": [
{ "data": "Symbol" },
{ "data": "CompanyName" },
{ "data": "StockType" },
{ "data": "ExDivDate" },
{ "data": "Dividend" },
{ "data": "DivYield" },
{ "data": "DivFrequency" },
{ "data": "DivPayDate" },
{ "data": "PriceToNav" },
{ "data": "AppreciationPotential" }
]
});

jquery datatable receive incorect json from webAPI

i can't populate a jQuery Datatble from ajax command.
this is webAPI code (UtentiController):
' GET: api/Utenti
<HttpGet>
Public Function GetUtentis() As IEnumerable(Of Utenti)
Using WFe As WorkForceEntities = New WorkForceEntities
Return WFe.Utentis.ToList
End Using
End Function
this is client side code:
<script>
$(document).ready(function () {
var oTable = $('#myDatatable').DataTable({
paging: true,
sort: true,
searching: true,
"ajax": {
"url": '/api/utenti/',
"type": "get",
"datatype": "json",
error: function (xhr, status, error) {
alert(xhr.responseText);
}
},
"columns": [
{ "data": "Nome", "autoWidth": true },
{ "data": "Cognome", "autoWidth": true },
{ "data": "Username", "autoWidth": true },
{ "data": "GruppoDiLavoro", "autoWidth": true },
{ "data": "ProfiloFunzionalità", "autoWidth": true },
]
})
})
</script>
i think the problem is on json string. the ajax command return incorrect json, missing the initial substring {"data":
[
{
"IDutente": 2,
"Operatore": "Admin",
"Password": "1234",
"LivelloDiAccesso": 1,
"Nome": "Admin",
"Cognome": "Admin",
"Username": "Admin",
"GruppoDiLavoro": "Admin",
"ProfiloFunzionalità": "Admin",
"Attivo": true,
"DataCreazione": "2017-08-30T00:00:00",
"DataScadenza": "2025-12-31T00:00:00",
"Mail": "nothing"
},
{
"IDutente": 3,
"Operatore": "MS",
"Password": "1234",
"LivelloDiAccesso": 2,
"Nome": "Admin",
"Cognome": "S",
"Username": "M",
"GruppoDiLavoro": "Admin",
"ProfiloFunzionalità": "Admin",
"Attivo": true,
"DataCreazione": "2017-08-30T00:00:00",
"DataScadenza": "2025-12-31T00:00:00",
"Mail": "nothing"
}
]
if i load a json file like this ("ajax": "../UtentiData.json",)
{
"data": [
{
"IDutente": 2,
"Operatore": "Admin",
"Password": "1234",
"LivelloDiAccesso": 1,
"Nome": "Admin",
"Cognome": "Admin",
"Username": "Admin",
"GruppoDiLavoro": "Admin",
"ProfiloFunzionalità": "Admin",
"Attivo": true,
"DataCreazione": "2017-08-30T00:00:00",
"DataScadenza": "2025-12-31T00:00:00",
"Mail": "nothing"
},
{
"IDutente": 3,
"Operatore": "MS",
"Password": "1234",
"LivelloDiAccesso": 2,
"Nome": "Admin",
"Cognome": "S",
"Username": "M",
"GruppoDiLavoro": "Admin",
"ProfiloFunzionalità": "Admin",
"Attivo": true,
"DataCreazione": "2017-08-30T00:00:00",
"DataScadenza": "2025-12-31T00:00:00",
"Mail": "nothing"
}
]
}
the code work well and the jQuery Datatable is populate correctly.
what can i do to work fine with Json webAPI?
thanks
you could use a "Flat array data source".
Change your code to:
<script>
$(document).ready(function () {
var oTable = $('#myDatatable').DataTable({
paging: true,
sort: true,
searching: true,
"ajax": {
"url": '/api/utenti/',
"type": "get",
"dataSrc": "",
error: function (xhr, status, error) {
alert(xhr.responseText);
}
},
"columns": [
{ "data": "Nome", "autoWidth": true },
{ "data": "Cognome", "autoWidth": true },
{ "data": "Username", "autoWidth": true },
{ "data": "GruppoDiLavoro", "autoWidth": true },
{ "data": "ProfiloFunzionalità", "autoWidth": true },
]
})
})
See the example.

JSON error on using jquery datatable

[{"name":"aaa","firstname":"bbb","lastname":"ccc"},
{"name":"qqq","firstname":"eee","lastname":"mmm"},
{"name":"www","firstname":"ooo","lastname":"lll"}]
I am making ajax request to server, its returning the above json data.But i >am getting the json parse error
$(document).ready(function() {
$('#example').dataTable( {
"processing": true,
"serverSide": true,
"ajax": {
"url": "http://example",
"dataType": "jsonp",
"columns": [
{ "data": "name"},
{ "data": "firstname" },
{ "data": "lastname" }
]
}
} );
});
Your ajax attribute should not contain the column attribute.:
Code:
$(document).ready(function() {
$('#example').dataTable( {
"processing": true,
"serverSide": true,
"ajax": {
"url": "http://example",
"dataType": "jsonp"
},
"columns": [
{ "data": "name"},
{ "data": "firstname" },
{ "data": "lastname" }
]
} );
});

Categories