Uncaught TypeError: Cannot set property 'data' of null in datatable

Uncaught TypeError: Cannot set property 'data' of null in datatable

modismodis Posts: 6Questions: 3Answers: 0
edited March 2017 in Free community support

Hello I am fetching the records using json response from controller in MVC. All the records are returned successfully from the controller side to .cshtml page but at my view side it cannot bind data to datatable in .cshtml file and give me an error as follow.

Uncaught TypeError: Cannot set property 'data' of null
at ra (jquery.dataTables.min.js:35)
at Ub (jquery.dataTables.min.js:105)
at t.<anonymous> (jquery.dataTables.min.js:106)
at t.iterator (jquery.dataTables.min.js:97)
at t.<anonymous> (jquery.dataTables.min.js:106)
at Object.reload (jquery.dataTables.min.js:100)
at Object.complete (RejectedTransactions:697)
at l (jquery?v=aVgyEaZfAxZS60CT-VlCELEfaJJd3gsmIEC_bIC2LQQ1:1)
at Object.fireWith (jquery?v=aVgyEaZfAxZS60CT-VlCELEfaJJd3gsmIEC_bIC2LQQ1:1)
at w (jquery?v=aVgyEaZfAxZS60CT-VlCELEfaJJd3gsmIEC_bIC2LQQ1:1)

My Controller's code is as follow,

[HttpPost]
        [Authorize]
        public JsonResult GetRejectedMerchantTransactions(string mobileNumber, DateTime? fromDate, DateTime? toDate, string fromTime, string toTime)
        {
            string sMessage = string.Empty;
            bool bError = false;
            bool bStatus = true;

            List<MerchantTransactionModel> lstMerchantTransactionModel = new List<MerchantTransactionModel>();
            try
            {
                string shortFromDate = "";
                string shortToDate = "";
                string fromFinalDate = string.Empty;
                string toFinalDate = string.Empty;

                if (fromDate.HasValue && fromTime.Length > 1)
                {
                    shortFromDate = fromDate.Value.ToShortDateString();
                    fromFinalDate = shortFromDate + " " + fromTime;
                }

                if (toDate.HasValue && toTime.Length > 1)
                {
                    shortToDate = toDate.Value.ToShortDateString();
                    toFinalDate = shortToDate + " " + toTime;
                }

                List<TransactionStatusModel> lstTransactionStatusModel = GetTransactionStatusList();

                TransactionService.TransactionServiceClient transactionServiceClient = new TransactionService.TransactionServiceClient();
                TransactionService.GetRejectedMerchantTransactionsRequest getRejectedMerchantTransactionRequest = new TransactionService.GetRejectedMerchantTransactionsRequest()
                {
                    //MobileNumber = Convert.ToDecimal(mobileNumber),
                    //FromDate = !string.IsNullOrEmpty(fromFinalDate) ? Convert.ToDateTime(fromFinalDate) : fromDate,
                    //ToDate = !string.IsNullOrEmpty(toFinalDate) ? Convert.ToDateTime(toFinalDate) : toDate
                };

                TransactionService.GetRejectedMerchantTransactionsResponse getRejectedMerchantTransactionResponse = transactionServiceClient.GetRejectedMerchantTransactions(getRejectedMerchantTransactionRequest);

                if (getRejectedMerchantTransactionResponse != null)
                {
                    sMessage = getRejectedMerchantTransactionResponse.Message;
                    bError = false;
                    bStatus = true;

                    lstMerchantTransactionModel = getRejectedMerchantTransactionResponse.lstRejectedMerchantTransactions.Select(T => new MerchantTransactionModel
                    {
                        TransactionID = T.TransactionID,
                        TransactionPNRNumber = T.TransactionPNRNumber,
                        MobileNumber = T.MobileNumber,
                        IsSecondaryTxn = T.IsSecondaryTxn,
                        SecTxnYesNo = T.IsSecondaryTxn ? "Yes" : "No",
                        PTTxnRefNo = T.PTTxnRefNo,
                        TxnDate = T.TxnDateTime.ToString("dd-MMM-yyyy"),
                        TxnTime = T.TxnDateTime.ToString("hh:mm tt"),
                        MerchantName = T.MerchantName,
                        PGTxnRefNo = T.PGTxnRefNo,
                        Amount = T.Amount,
                        TxnStatusID = T.TxnStatusID,
                        TxnStatus = lstTransactionStatusModel.Where(ts => ts.StatusID == T.TxnStatusID).Select(ts => ts.Status).FirstOrDefault(),
                        TransactionSettlementID = T.TxnSettlementID,
                        SettlementFailureCount = T.SettlementFailureCount == null ? "-" : T.SettlementFailureCount.ToString(),
                        TransactionPaymentID = T.TransactionPaymentID,
                        PaymentMode = T.PaymentModes,
                        ChannelType = T.ChannelTypes
                    }).ToList();
                }
                else
                {
                    sMessage = getRejectedMerchantTransactionResponse.Message;
                    bStatus = false;
                    bError = true;
                }
            }
            catch (Exception ex)
            {
                CreateLog.Error(this.GetType(), "An error occured in GetRejectedMerchantTransactions", ex);
                ViewBag.Error = true;
                ViewBag.Message = "An error occured. Please try again.";
            }
            return Json(new { aaData = lstMerchantTransactionModel, Message = sMessage, Status = bStatus, Error = bError }, JsonRequestBehavior.AllowGet);
        }

and .cshtml file'd code is as follow

merchantTransactionsTable = $('#merchantTransactionsTable').DataTable({
"processing": true,
"stateSave": true,
"columns": [
{ "data": "TransactionPNRNumber" },
{ "data": "MobileNumber" },
{ "data": "PaymentMode" },
{ "data": "ChannelType" },
{ "data": "SecTxnYesNo" },
{ "data": "TransactionPNRNumber" },
{ "data": "TxnDate" },
{ "data": "TxnTime" },
{ "data": "MerchantName" },
{ "data": "TransactionPaymentID" },
{ "data": "SettlementFailureCount" },
{ "data": "Amount" },
{ "data": "TxnStatus" },
],
"columnDefs": [

                {
                    "render": function (data, type, row) {
                        return '<input class="selectRow" name="selectRow" type="checkbox" TransactionPNRNumber="' + data + '" />';

                    },
                    "targets": 0,
                    "bSortable": false,
                },
                {
                    "render": function (data, type, row) {
                        return '<span class="label label-warning">' + data + '</span>';
                    },
                    "targets": 10
                },
                {
                    "render": function (data, type, row) {
                        return '<span class="fa fa-inr"></span>&nbsp;' + data;
                    },
                    "targets": 11
                }
            ]
        });

        $("#search").bind("click", function (e) {
            DismissStatusBox();
            $('#example-select-all').prop('checked', false);
            if ($('#MobileNumber').val() == "" && $('#FromDate').val() == "" && $('#ToDate').val() == "" && $('#ToTime').val() == "" &&
                 $('#TransactionStatus').val() == "") {
                alert('Please choose atleast one of the filter');
            }
            else if (($('#FromTime').val() != "" && $('#FromDate').val() == "") || ($('#ToTime').val() != "" && $('#ToDate').val() == "")) {
                alert("Plese select proper date time");
            }
            else {
                var MobileNumber = $('#MobileNumber').val() == "" ? 0 : $("#MobileNumber").val();
                var FromDate = $('#FromDate').val() == "" ? 0 : new Date($('#FromDate').val());
                var FromTime = $('#FromTime').val() == "" ? 0 : $('#FromTime').val();
                var ToDate = $('#ToDate').val() == "" ? 0 : new Date($('#ToDate').val());
                var ToTime = $('#ToTime').val() == "" ? 0 : $("#ToTime").val();

                $.ajax({
                    contentType: 'application/json; charset=utf-8',
                    dataType: 'json',
                    type: "POST",
                    url: '@Url.Content("~/Merchant/GetRejectedMerchantTransactions")',
                    data: JSON.stringify({ mobileNumber: MobileNumber, fromDate: convert(FromDate), toDate: convert(ToDate), fromTime: FromTime, toTime: ToTime }),
                    complete: function () {
                        $('#example-select-all').prop('checked', false);
                        merchantTransactionsTable.ajax.reload();
                    }
                });
            }
        });

```
I have tried all my best using json data validator and by manually checking json respponse data. but coudnot find any issue. Kindly help me to resolve this.

Thanks in advance!

This question has an accepted answers - jump to answer

Answers

  • allanallan Posts: 61,446Questions: 1Answers: 10,054 Site admin

    Can you show me the JSON that is being returned by the server please?

    Allan

  • modismodis Posts: 6Questions: 3Answers: 0
    edited March 2017

    @allan - This is my response.

    {"aaData":[{"TransactionID":10784,"TransactionPNRNumber":"8945926","MobileNumber":9969845030,"IsSecondaryTxn":true,"SecTxnYesNo":"Yes","PTTxnRefNo":"JO9876178","TxnDate":"17-Feb-2017","TxnTime":"12:56 PM","MerchantName":"The Test business name","PGTxnRefNo":"190603123","Amount":3.00,"TxnStatusID":8,"TxnStatus":"SentToBank","TransactionSettlementID":null,"SettlementFailureCount":"-","MakerID":0,"LoggedInUserID":0,"TransactionPaymentID":"68657953","UniqueRequestNumber":null,"IsInitiated":false,"PaymentMode":"Debit Card","ChannelType":"IDBIBANK.LTD.","Remark":null,"SellerFlags":null},{"TransactionID":565,"TransactionPNRNumber":"9831890474","MobileNumber":9969845030,"IsSecondaryTxn":true,"SecTxnYesNo":"Yes","PTTxnRefNo":"JO9831340","TxnDate":"18-Mar-2016","TxnTime":"08:40 PM","MerchantName":"The Test business name","PGTxnRefNo":"137530640","Amount":12.34,"TxnStatusID":8,"TxnStatus":"SentToBank","TransactionSettlementID":null,"SettlementFailureCount":"-","MakerID":0,"LoggedInUserID":0,"TransactionPaymentID":"51094556","UniqueRequestNumber":null,"IsInitiated":false,"PaymentMode":"Credit/Debit Card","ChannelType":null,"Remark":null,"SellerFlags":null}],"Message":"Rejected merchant transaction list found.","Status":true,"Error":false}

  • allanallan Posts: 61,446Questions: 1Answers: 10,054 Site admin

    I think I see the issue - you don't use the ajax option in your DataTables initialisation. So you can't use the ajax.reload() method.

    It looks like you are actually getting the JSON data yourself, in which case you could just add it to DataTables using the rows.add() method.

    Allan

  • modismodis Posts: 6Questions: 3Answers: 0
    edited March 2017

    @allan on first page load i want to load my datatable as blank then after on serach button click i want to bind this json formatted response data to my datatable. would you help me to do that? as i have used the same method for one of my another page and it is working properly but in this case i am getting the above mentioned error with dialog box message as **datatables warning: table id=merchanTransactionsTable - Invalid JSON response. For more information about this error, please see http://datatables.net/tn/1**

  • allanallan Posts: 61,446Questions: 1Answers: 10,054 Site admin
    Answer ✓

    Could you run the debugger on the table when you get that error please, or link to the page.

    However, as I say, if you are making the Ajax call yourself, rather than using the ajax property (which isn't being used in the above code), you can't use the built in Ajax methods. You have to use rows.add() to add the data to the table.

    Allan

  • modismodis Posts: 6Questions: 3Answers: 0
    edited March 2017

    @allan I got your suggetion and made the ajax call using ajax option property while page first load and it worked for me fine.

    Thanks for your help!

  • badbytebadbyte Posts: 33Questions: 7Answers: 0

    I have a similar usecase.
    In my case I have reference data that is being stored in a variable in javascript that I would like datatables to reload it's data whenever the user would like to start from scratch when he/she isn't satisfied.
    This is what I tried to do:

    $('#table').DataTable().ajax.reload(originalJsonData,true)
    

    But with the same error message as above.
    Can someone point me to the right direction?

  • colincolin Posts: 15,112Questions: 1Answers: 2,583

    Hi @badbyte ,

    The first parameter to ajax.reload() is a callback function that's called when the data is loaded. If you want to use a variable containing data, I suspect you want data,

    Cheers,

    Colin

  • badbytebadbyte Posts: 33Questions: 7Answers: 0

    True, but in the third example, where you define the reload function what is the 'val' function. The description is a little short for one thing and the name of that function gives me the understanding that it accesses the value of the datatable.

  • allanallan Posts: 61,446Questions: 1Answers: 10,054 Site admin

    You've got the original data? So do use the ajax methods at all - do:

    table.clear().rows.add(originalJsonData).draw();
    

    Allan

  • kalpesh26kalpesh26 Posts: 1Questions: 0Answers: 0

    thanks @allan this work's for me

    table.clear().rows.add(originalJsonData).draw();

This discussion has been closed.