更新时间:2023-10-31 18:22:28
更新
我找到了一种更好的方法,可以将AJAX用于来自Controller的源数据.请将此方法用于带有AJAX的DataTable网格:
I found a better way to use AJAX for your source data from the Controller. Please use this method for your DataTable grid with AJAX:
为了在DataTable插件中通过AJAX显示数据,请在代码中进行以下更改:
In order to show your data via AJAX in your DataTable plugin, make the following changes in your code:
添加一个名为DataTable
public class DataTable
{
public List<vt> data { get; set; }
}
然后在您的控制器中
public JsonResult GetVoters()
{
DataTable dataTable = new DataTable();
List<vt> stud = (from student in _context.Voters
select new vt
{
StudentNumber = student.StudentNumber,
Name = student.Name,
Faculty = student.Faculty,
Department = student.Department,
Program = student.Program,
Code = student.Code
}).Take(100).ToList();
//The magic happens here
dataTable.data = stud;
return Json(dataTable, JsonRequestBehavior.AllowGet);
}
最后在您的View中,使用以下脚本填充您的DataTable:
And finally in your View, use this script to populate your DataTable:
<script type="text/javascript">
$(document).ready(function () {
//For filtering:
$('#codetable thead tr').clone(true).appendTo('#codetable thead');
$('#codetable thead tr:eq(1) th').each(function (i) {
var title = $(this).text();
$(this).html('<input type="text" placeholder="Search ' + title + '" />');
$('input', this).on('keyup change', function () {
if (table.column(i).search() !== this.value) {
table
.column(i)
.search(this.value)
.draw();
}
});
});
var table=$('#codetable').DataTable({
"ajax": '@Url.Action("GetVoters", "Index")',
"columns": [
{ "data": "StudentNumber" },
{ "data": "Name" },
{ "data": "Faculty" },
{ "data": "Department" },
{ "data": "Program" },
{ "data": "Code" }
]
});
});
</script>
而且我几乎忘记了,出于过滤目的,还更改了HTML表的结构:
And I almost forgot, change the structure of your HTML table also for your filtering purpose:
<table class="table table-striped" id="codetable">
<thead>
<tr>
<th>Student Number</th>
<th>Student</th>
<th>Faculty</th>
<th>Department</th>
<th>Program</th>
<th>Code</th>
</tr>
</thead>
<tbody></tbody>
</table>
我已将DataTables与 AJAX对象用作网格的数据源.
I have used DataTables with AJAX objects as datasource for your grid.
干杯.