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

Posted

技术标签:

【中文标题】如何在 mvc 中使用 ajax 将数据加载到数据表中【英文标题】:How to load data into datatable using ajax in mvc 【发布时间】:2019-08-21 04:18:30 【问题描述】:

我正在使用 ajax 将数据库中的对象列表加载到数据表中。调试时,我的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; 

我希望表格显示列表中的各个列,但会引发此错误“DataTables 警告:表格 id=codetable - 请求第 0 行、第 1 列的未知参数 '1'...”并仅在第一列(因此每行一个字符)。其余列显示为空

Displayed Error

【问题讨论】:

完成您的代码。 Atction、ajax、数据表渲染 【参考方案1】:

更新

我找到了一种更好的方法来使用 AJAX 处理来自控制器的源数据。请将此方法用于带有 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 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 的 DataTables 作为您网格的数据源。

干杯。

【讨论】:

数据加载正常,谢谢,但搜索和分页不起作用,尽管我已将 bFilter 设置为 true 您必须明确添加这些过滤器,其中也包括您的搜索。由于您将数据发布到服务器,因此您需要从列表中过滤和搜索。 @Shagragada 请通过搜索和过滤找到更新的答案以及通过 AJAX 初始化 DataTable 的更好方法。 请为此发布一个新问题。 数据没有为我加载@Rahul Sharma,没有任何错误【参考方案2】:

当我从 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" 
        ]
    );
);

【讨论】:

此链接将让您深入了解 API 在这种情况下工作的原因:***.com/questions/9494966/…

以上是关于如何在 mvc 中使用 ajax 将数据加载到数据表中的主要内容,如果未能解决你的问题,请参考以下文章