jquery dataTables - how to add an edit and delete option
Here you have an example assuming the following:
- Ajax population
- Data row is an array containing 4 columns
- Your data row contains the id on first column
- You don't display id on table so you hide it
It shouldn't be hard to adapt it to your needs. Check columns
usage
var datatablesOptions = {
"serverSide": true,
"ajaxSource": '[yourAjaxUrl]',
"processing": true,
"columns": [
{ bVisible = false }, // assume this is the id of the row, so don't show it
null,
null,
null,
/* EDIT */ {
mRender: function (data, type, row) {
return '<a class="table-edit" data-id="' + row[0] + '">EDIT</a>'
}
}
/* DELETE */ {
mRender: function (data, type, row) {
return '<a class="table-delete" data-id="' + row[0] + '">DELETE</a>'
}
},
]
};
$('#table').dataTable(datatablesOptions);
EDIT
In case you need to conditional render something different depending on destination
you could do
mRender: function (data, type, row) {
if (row.destination == "d1") {
return '<a href="destination1?id=' + row.id + '">EDIT</a>'
}else (row.destination == "d2"){
return '<a href="destination2?id=' + row.id + '">EDIT</a>'
} else {
// some error telling that destination value is unexpected
}
}
take look at my Snippet of Columns part
columns: [
{ 'data': 'LastName' },
{ 'data': 'FirstMidName' },
{ 'data': 'EnrollmentDate' },
{// this is Actions Column
mRender: function (data, type, row) {
var linkEdit = '@Html.ActionLink("Edit", "Edit", new {id= -1 })';
linkEdit = linkEdit.replace("-1", row.ID);
var linkDetails = '@Html.ActionLink("Details", "Details", new {id= -1 })';
linkDetails = linkDetails.replace("-1", row.ID);
var linkDelete = '@Html.ActionLink("Delete", "Delete", new {id= -1 })';
linkDelete = linkDelete.replace("-1", row.ID);
return linkDetails + " | " + linkEdit + " | " + linkDelete;
}
}
and this is snippet from my Json
{ID: 1, LastName: "Alexander", FirstMidName: "Carson", EnrollmentDate: "/Date(1126386000000)/",…}
Note thate I'm using ASP.Net MVC so Html.ActionLink
just returning a Link
and the results are