0

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).

ASP.NET MVC 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<Requisition>()
            .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: '<svg xmlns="http://www.w3.org/2000/svg" width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="feather feather-plus"><line x1="12" y1="5" x2="12" y2="19"></line><line x1="5" y1="12" x2="19" y2="12"></line></svg> New',
                            formOptions: {
                                submitTrigger: 6,
                                submitHtml: '<i class="fa fa-play"/>'
                            }
                        },
                        {
                            extend: 'selectAll',
                            text: '<i class="fa fa-check"></i> <span style="font-size:16px">Select All</span>',
                            className: 'btn-space'
                        },
                        {
                            extend: 'selectNone',
                            text: '<i class="fa fa-times-circle"></i> <span style="font-size:16px">Deselect all</span>'
                        } 
                    ]
                });

Here is a gist of the response response.txt

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.