Reputation: 154
I need to update the OrderIndex
value inside database by row-reorder function in datatables (www.datatables.net).
I have already searched in google and I found this article. I followed all of the steps but it didn't help.
Please let me know if you need more information. Thank you
public class GenderDDUpdateOrderIndexViewModel
{
public int Id { get; set; }
public int OrderIndex { get; set; }
}
public async Task<ActionResult> UpdateRowIndex(GenderDDUpdateOrderIndexViewModel model, int? Id, int? fromPosition, int toPosition, string direction)
{
using (var ctx = new ApplicationIdentityDbContext())
{
if (direction == "back")
{
var GenderList = ctx.GenderDD
.Where(c => (toPosition <= c.OrderIndex && c.OrderIndex <= fromPosition))
.ToList();
foreach (var gender in GenderList)
{
gender.OrderIndex++;
}
}
else
{
var GenderList = ctx.GenderDD
.Where(c => (fromPosition <= c.OrderIndex && c.OrderIndex <= toPosition))
.ToList();
foreach (var gender in GenderList)
{
gender.OrderIndex--;
}
}
ctx.GenderDD.First(c => c.Id == Id).OrderIndex = toPosition;
await ctx.SaveChangesAsync();
}
return View();
}
<script>
$(document).ready(function() {
var table = $('#GenderIndex').DataTable({
"paging": true,
"pagingType": "full_numbers",
rowReorder: {
snapX: 10
}
});
});
</script>
Upvotes: 3
Views: 3730
Reputation: 907
Above mentioned plug-in won't work since it's extremely old. You can easily use DataTables RowReorder extension. You don't need to write such a long action method since many of those parameters are not supported by the latest version of DataTables.
public void UpdateRow(GenderDDUpdateOrderIndexViewModel model, int Id, int fromPosition, int toPosition)
{
using (var ctx = new ApplicationIdentityDbContext())
{
var GenderList = ctx.GenderDD.ToList();
ctx.GenderDD.First(c => c.OrderIndex == Id).OrderIndex = toPosition;
ctx.SaveChanges();
}
}
<script type="text/javascript">
var table = $('#GenderIndex').DataTable({
rowReorder: true,
"paging": true,
"pagingType": "full_numbers",
fixedHeader: true,
select: false,
"order": [[0, "asc"]],
"info": true,
"processing": false,
"responsive": true,
"searching": true,
"lengthMenu": [[10, 25, 50, -1], [10, 25, 50, "All"]],
"language": {
"lengthMenu": "_MENU_",
"zeroRecords": "No records found",
"infoEmpty": "No records found",
"infoFiltered": "(filtered from _MAX_ total records)"
},
"columnDefs": [
{ "orderable": false, "targets": 8 }
]
});
$('#GenderIndex').on('row-reorder.dt', function (dragEvent, data, nodes) {
for (var i = 0, ien = data.length ; i < ien ; i++) {
var rowData = table.row(data[i].node).data();
$.ajax({
type: "GET",
cache: false,
contentType: "application/json; charset=utf-8",
url: '/GenderDD/UpdateRow',
data: { Id: rowData[0], fromPosition: data[i].oldData, toPosition: data[i].newData },
dataType: "json"
});
}
});
</script>
Upvotes: 6