如何在 mvc 中使用 ajax 将数据加载到数据表中

How to load data into datatable using ajax in mvc

我正在使用 ajax 将对象列表从数据库加载到数据 table 中。调试时,我的 MVC 操作结果似乎可以查询数据,但 datatable 列显示 null

我尝试在 MVC 操作中返回之前序列化列表,但它没有解决问题

// Code from View

<table class="table table-striped" id="codetable">
<thead>
    <tr>
        <td>Student Number</td>
        <td>Student</td>
        <td>Faculty</td>
        <td>Department</td>
        <td>Program</td>
        <td>Code</td>
    </tr>
</thead>
<tbody>

</tbody>
</table>

<script>
    $(document).ready(function () {
        $("#codetable").DataTable({
            processing: true,
            serverSide: true,
            info: true,
            ajax: {
                url: '@Url.Action("GetVoters", "Index")',
                dataSrc: ""
            },

            Columns: [
                { "data": "StudentNumber" },
                { "data": "Name" },
                { "data": "Faculty" },
                { "data": "Department" },
                { "data": "Program" },
                { "data": "Code" }
            ]
        });
    });
</script>


//Code from Controller

public JsonResult GetVoters()
{
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();
        var js = new System.Web.Script.Serialization.JavaScriptSerializer();
        var result = js.Serialize(stud);
        return Json(result, JsonRequestBehavior.AllowGet);
    }

public class vt
{
    public string StudentNumber { get; set; }
    public string Name { get; set; }
    public string Faculty { get; set; }
    public string Department { get; set; }
    public string Program { get; set; }
    public string Code { get; set; }
}

我希望 table 显示列表中的各个列,但抛出此错误 "DataTables warning: table id=codetable - Requested Unknown parameter '1' for row 0, column 1..." 并仅在第一列中显示结果(因此每行一个字符)。其余列显示为 null

Displayed Error

更新

我找到了一种更好的方法来使用 AJAX 来自 Controller 的源数据。请将此方法用于 AJAX:

的 DataTable 网格

为了在您的 DataTable 插件中通过 AJAX 显示您的数据,请在您的代码中进行以下更改:

添加一个名为 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);
  }

最后在您的视图中,使用此脚本填充您的数据表:

 <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 table 的结构也是为了您的过滤目的:

<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>

我已经使用带有 AJAX objects 的数据表作为您的网格的数据源。

干杯。

当我从 API 而不是控制器读取数据时,它也起作用了。在这种情况下,DataTables 保留了其默认的过滤、​​排序和分页。调试时,API 和Controller JsonResult 返回的数据格式看起来是一样的。我真的无法解释为什么 API 可以工作而控制器却不能。

//The API Code

public IEnumerable<vt> GetStudents()
    {
        return _context.Voters.Select(x=>new vt { StudentNumber = x.StudentNumber, Name = x.Name, Faculty = x.Faculty, Department = x.Department, Program = x.Program, Code = x.Code }).ToList();
    }



//The only change in the jquery script is the url which now points to the API

<script>
$(document).ready(function () {
    $("#codetable").DataTable({
        processing: true,
        serverSide: true,
        info: true,
        ajax: {
            url: "/api/Students",
            dataSrc: ""
        },

        Columns: [
            { "data": "StudentNumber" },
            { "data": "Name" },
            { "data": "Faculty" },
            { "data": "Department" },
            { "data": "Program" },
            { "data": "Code" }
        ]
    });
});