如何在MVC中使用Ajax将数据加载到数据表中

时间:2019-03-30 10:58:52

标签: c# jquery asp.net-mvc datatables asp.net-ajax

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

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

Displayed Error

2 个答案:

答案 0 :(得分:0)

更新

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

最后在您的View中,使用以下脚本填充您的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表的结构:

<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用作网格的数据源。

干杯。

答案 1 :(得分:0)

当我从API而不是从Controller读取数据时,它也起作用。在这种情况下,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" }
        ]
    });
});