微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

DataTable不显示数据

如何解决DataTable不显示数据

我正在尝试使用Datatable,但在.net核心项目中填充Datatable时遇到问题。加载页面时,DataTable记录为空。如下图所示:

enter image description here

控制器:

 public IActionResult ShowCategory()
        {
            return View();
        }


 public IActionResult CategoryList()
        {
            try
            {
                var draw = HttpContext.Request.Form["draw"].FirstOrDefault();
                // Skiping number of Rows count
                var start = Request.Form["start"].FirstOrDefault();
                // Paging Length 10,20
                var length = Request.Form["length"].FirstOrDefault();
                // Sort Column Name
                var sortColumn = Request.Form["columns[" + Request.Form["order[0][column]"].FirstOrDefault() + "][name]"].FirstOrDefault();
                // Sort Column Direction ( asc,desc)
                var sortColumnDirection = Request.Form["order[0][dir]"].FirstOrDefault();
                // Search Value from (Search Box)
                var searchValue = Request.Form["search[value]"].FirstOrDefault()   
                
               var data = _categoryRepository.GetCategories();

            
                return Json(new { draw = 1,recordsFiltered = 4,recordsTotal = 4,data = data });
         
            }

            catch(Exception ex)
            {
                throw;
            }
        
            
         }

由于代码有问题,我现在将绘图和...作为硬编码传递给了View。

GetCategories() method:
public List<Categoryviewmodel> GetCategories()
        {
            

            var query = _CategoryRepo.GetAll();

            var q = query.Select(s => new Categoryviewmodel
            {
                Id = s.Id,CaregoryParentId = s.CaregoryParentId,Priority = s.Priority,Title = s.Title
            }).ToList();

         
            return q;
        }

视图:

@{
    Layout = null;
}

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<link href="~/css/admin/bootstrap.min.css" rel="stylesheet" />

<link href="https://cdn.datatables.net/1.10.15/css/dataTables.bootstrap.min.css" rel="stylesheet" />
<link href="https://cdn.datatables.net/responsive/2.1.1/css/responsive.bootstrap.min.css" rel="stylesheet" />

<script src="https://cdn.datatables.net/1.10.15/js/jquery.dataTables.min.js"></script>
<script src="https://cdn.datatables.net/1.10.15/js/dataTables.bootstrap4.min.js "></script>

<div class="container">
    <br />
    <div style="width:90%; margin:0 auto;">
        <table id="example" class="table table-striped table-bordered dt-responsive Nowrap" width="100%" cellspacing="0">
            <thead>
                <tr>
                    <th>Id</th>
                    <th>Title</th>
                    <th>CaregoryParentId</th>
                    <th>Priority</th>
                    <th>Edit</th>
                    <th>Delete</th>
                </tr>
            </thead>
        </table>
    </div>
</div>

<script>

        $(document).ready(function ()
        {

            $("#example").DataTable({
                "processing": true,// for show progress bar
                "serverSide": true,// for process server side
                "filter": true,// this is for disable filter (search Box)
                "orderMulti": false,// for disable multiple column at once
                "ajax": {
                    "url": "/Admin/Category/CategoryList","type": "POST","datatype": "json"
               
                    //"success": function (data) {
                    //    alert(JSON.stringify(data));
                    //}
                },"columnDefs":
                [{
                    "targets": [0],"visible": false,"searchable": false
                }],{ "data": "Id","name": "Id","autoWidth": true },{ "data": "Title","name": "Title",{ "data": "CaregoryParentId","name": "CaregoryParentId",{ "data": "Priority","name": "Priority",{
                        "render": function (data,type,full,Meta)
                        { return '<a class="btn btn-info" href="/Demogrid/Edit/' + full.CustomerID + '">Edit</a>'; }
                    },{
                        data: null,render: function (data,row)
                        {
                            return "<a href='#' class='btn btn-danger' onclick=DeleteData('" + row.CustomerID + "'); >Delete</a>";
                        }
                    },]

            });
        });


    function DeleteData(CustomerID)
        {
            if (confirm("Are you sure you want to delete ...?"))
            {
                Delete(CustomerID);
            }
            else
            {
                return false;
            }
        }


        function Delete(CustomerID)
    {
        var url = '@Url.Content("~/")' + "Demogrid/Delete";

        $.post(url,{ ID: CustomerID },function (data)
                {
                    if (data)
                    {
                        oTable = $('#example').DataTable();
                        oTable.draw();
                    }
                    else
                    {
                        alert("Something Went Wrong!");
                    }
                });
    }

</script>

当我调试时,我在Ajax成功函数中接收到数据,但未在表中显示。 有谁能够帮助我? 非常感谢

解决方法

当我调试时,我在Ajax成功函数中接收到数据,但不是 显示在表格中。

enter image description here

从上面的结果中我们可以看到,服务器返回默认情况下使用驼峰式案例名称对JSON进行序列化。

  • Id => id
  • Title => title
  • CaregoryParentId => caregoryParentId
  • Priority => priority

但是在您的脚本中,“数据”被设置为“ Id”。



解决方案

使用以下代码默认情况下避免使用骆驼箱名称。

        services.AddControllersWithViews().AddJsonOptions(opts => opts.JsonSerializerOptions.PropertyNamingPolicy = null);

JS代码

   $(document).ready(function ()
    {

        $("#example").DataTable({
            "processing": true,// for show progress bar
            "serverSide": true,// for process server side
            "filter": true,// this is for disable filter (search box)
            "orderMulti": false,// for disable multiple column at once
            "ajax": {
                "url": "/Admin/Category/CategoryList","type": "POST","datatype": "json",//"success": function (data) {
                //    alert(JSON.stringify(data));
                //}
            },"columnDefs":
            [{
                "targets": [0],"visible": false,"searchable": false
            }],"columns": [
                { "data": "Id","name": "Id","autoWidth": true },{ "data": "Title","name": "Title",{ "data": "CaregoryParentId","name": "CaregoryParentId",{ "data": "Priority","name": "Priority",{
                    "render": function (data,type,full,meta) { return '<a class="btn btn-info" href="/DemoGrid/Edit/' + full.CustomerID + '">Edit</a>'; }
                },{
                    data: null,render: function (data,row) {
                        return "<a href='#' class='btn btn-danger' onclick=DeleteData('" + row.CustomerID + "'); >Delete</a>";
                    }
                }
            ]

        });
    });



结果测试

enter image description here

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。