我需要通过数据表 (www.datatables.net) 中的行重新排序函数更新数据库中的 OrderIndex
值。
我已经在 google 中搜索过了,我找到了这个 article .我遵循了所有步骤,但没有帮助。
如果您需要更多信息,请告诉我。谢谢
View 模型
public class GenderDDUpdateOrderIndexViewModel
{
public int Id { get; set; }
public int OrderIndex { get; set; }
}
Controller
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>
最佳答案
上面提到的插件不会工作,因为它太旧了。您可以轻松使用 DataTables RowReorder扩大。 您不需要编写这么长的操作方法,因为最新版本的 DataTables 不支持其中许多参数。
Controller
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();
}
}
jQuery
<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>
关于c# - 在 ASP.Net MVC 5 中使用 DataTables 行重新排序更新值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33469000/