如何在MVC中使用Ajax将数据加载到数据表中 [英] How to load data into datatable using ajax in mvc

查看:80
本文介绍了如何在MVC中使用Ajax将数据加载到数据表中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm loading List of objects from database into datatable using ajax. When debugging, the my MVC action result seem to query the data alright but the datatable column displays null

在MVC操作返回列表之前,我曾尝试对列表进行序列化,但是并不能解决问题

I've tried to serialize the list before returning it in the MVC action but it didn't solve the problem

// 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-请求的未知参数'1'为第0行,第1列...",并且仅在第一列(因此每行一个字符).其余各列显示为空

I expect the table to display various columns in the list but is throws this error "DataTables warning: table id=codetable - Requested Unknown parameter '1' for row 0, column 1..." and displays results only in the first column(thus a character per row). The rest of the columns show null

显示的错误

推荐答案

更新

我找到了一种更好的方法,可以将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.

干杯.

这篇关于如何在MVC中使用Ajax将数据加载到数据表中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆