n.e
n.e

Reputation: 93

DataTable doesn't show data

I am trying to use Datatable and I have an issue with Datatable populating data in my .net core project.When the page is loaded, DataTable records are empty.According to the picture below:

enter image description here

Controller:

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

Due to a problem with the code, I have now passed the draw and ... to View as a hardcode.

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

view:

@{
    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", "autoWidth": true },
                { "data": "CaregoryParentId", "name": "CaregoryParentId", "autoWidth": true },
                { "data": "Priority", "name": "Priority", "autoWidth": true },
                
                    {
                        "render": function (data, type, full, meta)
                        { return '<a class="btn btn-info" href="/DemoGrid/Edit/' + full.CustomerID + '">Edit</a>'; }
                    },
                    {
                        data: null, render: function (data, type, 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>

when I debug, I receive data in Ajax success function, but it is not shown in the table. can anybody help me? Thanks a lot

Upvotes: 1

Views: 1056

Answers (1)

Michael Wang
Michael Wang

Reputation: 4022

when I debug, I receive data in Ajax success function, but it is not shown in the table.

enter image description here

From the result above we can see, server return serializes JSON with camel case names by default.

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

But in your script, "data" is set as "Id".



Solution

Use the codes below to avoid camel case names by default.

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

Codes of 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", "autoWidth": true },
                { "data": "CaregoryParentId", "name": "CaregoryParentId", "autoWidth": true },
                { "data": "Priority", "name": "Priority", "autoWidth": true },
                {
                    "render": function (data, type, full, meta) { return '<a class="btn btn-info" href="/DemoGrid/Edit/' + full.CustomerID + '">Edit</a>'; }
                },
                {
                    data: null, render: function (data, type, row) {
                        return "<a href='#' class='btn btn-danger' onclick=DeleteData('" + row.CustomerID + "'); >Delete</a>";
                    }
                }
            ]

        });
    });



Test of result

enter image description here

Upvotes: 1

Related Questions