• Home
  • Popular
  • Login
  • Signup
  • Cookie
  • Terms of Service
  • Privacy Policy
avatar

Posted by User Bot


26 Apr, 2025

Updated at 20 May, 2025

DataTable is always empty .Net MVC

I am working with jquery datatables but the datatable is always empty when the page loads. On inspecting the network tab, the request returns an empty response but when debugging the controller request method, the response contains a DtResponse object with the data having a count of 2. Interestingly, when I return the data part of the DtResponse (response.data), the response is returned to the frontend. (Not the case otherwise)

.Net Controller Method

public ActionResult CRUD()
    {
        try
        {
            logger.LogInformation("Creating requisition"); 
            var user = AuthService.GetUserDetails(User);
            using var db = new Database(StaticVariables.DbType, StaticVariables.ConnectionStringApi, StaticVariables.DbAdapter);
            var response = new Editor(db, "Requisition", "ID")
                .Model()
                .Field(new Field("Item_ID")
                    .Validator(Validation.NotEmpty())
                    .Validator(Validation.Numeric())
                )
                .Field(new Field("Cost")
                    .SetValue(0)
                )
                .Field(new Field("DetailedDescription")  
                )
                .Field(new Field("Qty")
                    .Validator(Validation.Numeric())
                ) 
                .Field(new Field("User_ID")
                        .SetValue(user.ID)
                )
                .Field(new Field("StatusChangeDate")
                        .SetValue(DateTime.Now)
                )
                .Field(new Field("Subsidiary_ID")
                        .SetValue(user.Subsidiary_ID) 
                )
                .Field(new Field("Unit_ID")
                        .SetValue(user.Unit_ID) 
                )
                .Field(new Field("Department_ID")
                        .SetValue(user.Department_ID) 
                ) 
                .Field(new Field("Location_ID")
                        .SetValue(user.Location_ID) 
                ) 
                .Field(new Field("Status")
                        .SetValue("Added") 
                )
                .Field(new Field("is_deleted")
                        .SetValue(false) 
                )
                .Field(new Field("DateRequested")
                    .Validator(Validation.DateFormat(
                        "yyyy-MM-dd HH:mm:ss",
                        new ValidationOpts { Message = "Please enter a date in the format yyyy-MM-dd HH:mm:ss" }
                    ))
                    .GetFormatter(Format.DateSqlToFormat("yyyy-MM-dd HH:mm:ss"))
                    .SetFormatter(Format.DateFormatToSql("yyyy-MM-dd HH:mm:ss")) 
                )
                .TryCatch(false)
                .Process(Request)
                .Debug(true)
                .Data();  
            Console.WriteLine(JsonConvert.SerializeObject(response, Formatting.Indented));
            return Json(response); 
        }
        catch (Exception e)
        {
            logger.LogError(e,"Error occurred in {method}", nameof(CRUD));
            return Json(new { error = "Something went wrong. Please try again." });
        }
    }

Datatable Javascript

const requisitionEditor = new $.fn.dataTable.Editor({
                    ajax: "/Requisition/CRUD",
                    table: "#reqPreview",
                    fields: [
                        {label: "Item:", name: "Item_ID", type: "select", placeholder: "Select an Item"},
                        {label: "Quantity:", name: "Qty"}, 
                        {
                            label: "Date Requested:", name: "DateRequested",
                            type: 'datetime',
                            def: function () {
                                return new Date();
                            },
                            format: 'yyyy-MM-DD HH:mm:ss', 
                            opts: {
                                minutesIncrement: 5
                            }
                        },
                        {label: "Detailed Description:", name: "DetailedDescription"},
                    ]
                });

let createPreviewRequisition = $('#reqPreview').DataTable({
                    dom: "Bfrtip",
                    ajax: {
                        url: "/Requisition/CRUD", 
                        dataSrc: function(response) {
                            console.log('response', response);
                            if(shouldStoreLocal) {
                                return localRequests;
                            }
                            return response;
                        }
                    },
                    paging: false,
                    paginate: true,
                    info: true,
                    columns: [
                        {"data": "ID", searchable: true},
                        {"data": "ItemName",editField: "Item_ID"},
                        {"data": "Cost"},
                        {"data": "Qty"},
                        {"data": "DateRequested"},
                        {"data": "DetailedDescription"},
                        {
                            data: null, 
                            orderable: false,
                            width : '50px' 
                        }
                    ],
                    select: {
                        style: 'os',
                        selector: 'td:first-child'
                    },
                    columnDefs: [
                        { targets: '_all', className: 'dt-center' }
                    ],
                    buttons: [
                        {
                            extend: 'createInline',
                            editor: requisitionEditor,
                            text: ' New',
                            formOptions: {
                                submitTrigger: 6,
                                submitHtml: ''
                            }
                        },
                        {
                            extend: 'selectAll',
                            text: ' Select All',
                            className: 'btn-space'
                        },
                        {
                            extend: 'selectNone',
                            text: ' Deselect all'
                        } 
                    ]
                });

Here is a gist of the response response.txt