Reputation: 2629
I want to add 2 extra columns (edit and delete) in my datatable. each row in my datatable contains a hidden columns which is the record ID, so when users click on edit or delete i would like to get selected row Id.
$(document).ready(function() {
var mytable = $('#userTable').DataTable({
"fixedHeader": {
"header": true,
"footer": true
},
"lengthMenu": [[25, 50, 100, 200, -1], [25, 50, 100, 200, "All"]],
"ajax": {
"url": "/Users/Prov",
"type": "Get",
"data": { "id": "@userId", "cityId": "@cityId" },
"datatype": "json"
},
"columnDefs": [
{
"targets": -1,
"data": null,
"defaultContent": "<button>Delete!</button>"
}
],
"columns": [
{ "data": "Id", "visible": false, "searchable": false },
{ "data": "Name" },
{ "data": "City" },
{ "data': "Code" },
{ "data': "Title" },
]
});
$('#userTable tbody').on('click', 'button', function() {
var rowData = mytable.row($(this).parents('tr')).data();
alert(rowData[1] + "'s City is: " + rowData[2]);
});
});
Upvotes: 0
Views: 5253
Reputation: 62498
You would need to add another column with edit hyperlink by specifying a new column in columns array property of datatables and then pass the id to the edit action via query string like:
"columns": [
{ "data": "Id", "visible": false, "searchable": false },
{ "data": "Name" },
{ "data": "City" },
{ "data": "Code" },
{ "data": "Title" },
{
"title": "Edit",
"data": "Id",
"searchable": false,
"sortable": false,
"render": function (data, type, full, meta) {
return '<a href="@Url.Action("Edit","Users")?id=' + data + '" class="editUser">Edit</a>';
}
]
it will call the edit controller with the id passed as parameter, and your edit action would be like:
public ActionResult Edit(int id)
{
// do the business logic here
}
The same way you can add details and delete button as well.
Upvotes: 3