locked
can not solve datatable error http://datatables.net/tn/4 RRS feed

  • Question

  • User-259252065 posted

    I'm implementing asp.net core 3.1. I have a JQuery Datatable that its first column has checkboxes. and I want after user checks some of rows then a message shows the selected rows' information to the user and according to what user previously selected a button, it should change the status of those selected data and update the status of those data in DataTable. Now for updating those data, I get the following error: DataTables warning: table id=myDummyTable - Requested unknown parameter 'productRequestNo' for row 4, column 2. For more information about this error, please see http://datatables.net/tn/4

    <div class="postcell post-layout--right"> <div class="s-prose js-post-body" itemprop="text">

    Here is what I have tried till now:

    Here is controller
    
    
    
    using Microsoft.AspNetCore.Mvc;
    using Microsoft.AspNetCore.Mvc.Rendering;
    using Microsoft.EntityFrameworkCore;
    using System;
    using System.Collections.Generic;
    using System.Data;
    using System.Diagnostics;
    using System.Linq;
    using System.Threading.Tasks;
    using OfficeOpenXml;
    using OfficeOpenXml.Style;
    using System.IO;
    using static Microsoft.EntityFrameworkCore.DbLoggerCategory;
    using System.Collections;
    using Microsoft.AspNetCore.Authorization;
    using Microsoft.AspNetCore.Http;
    
    using System.Linq.Dynamic.Core;
    using Newtonsoft.Json;
    
    namespace project.Controllers
    {
    
    
        public class productrequestersController : Controller
        {
            private readonly projectContext _context;
            private MyCookie mycookie;
          
    
            private readonly LDap.IAuthenticationService _authenticationService;
    
            public productrequestersController(LDap.IAuthenticationService authenticationService, projectContext context, IHttpContextAccessor ihttp)
            {
               
                _context = context;
    
                _authenticationService = authenticationService;
    
                mycookie = new MyCookie(ihttp);
            }
    
      
          
    
            //----------------------------------------------------------------------
            [HttpPost]
            public JsonResult GetproductrequestersData()
            {
    
                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[1][column]"].FirstOrDefault() + "][name]"].FirstOrDefault();
                    // Sort Column Direction ( asc ,desc)  
                    var sortColumnDirection = Request.Form["order[1][dir]"].FirstOrDefault();
                    // Search Value from (Search box)  
                    var searchValue = Request.Form["search[value]"].FirstOrDefault();
    
                    //Paging Size (10,20,50,100)  
                    int pageSize = length != null ? Convert.ToInt32(length) : 0;
                    int skip = start != null ? Convert.ToInt32(start) : 0;
                    int recordsTotal = 0;
    
    
                    var vwReportData = from t in _context.VwReport
                                       where t.IsDeleted == false
                                       select new
                                       {
                                           id1 = t.Id,
                                           id = t.Id,
                                           productRequestNo = t.productRequestNo,
                                           requesterName = t.requesterName,
                                           productName = t.productName,
                                           productRequestDate = t.productRequestDate,
                                           logDate = t.LogDate,
                                           itemName = t.itemName,
                                           lastReqStatus = t.LastReqStatus
                                       };
    
    
    
                    if (!(string.IsNullOrEmpty(sortColumn) && string.IsNullOrEmpty(sortColumnDirection)))
                    {
                        vwReportData = vwReportData.OrderBy(sortColumn + " " + sortColumnDirection);
                    }
                    //Search  
                    if (!string.IsNullOrEmpty(searchValue))
                    {
                        searchValue = searchValue.Trim();
                        vwReportData = vwReportData.Where(m => m.productRequestNo.ToString() == searchValue || m.productName.Trim().Contains(searchValue) || m.logDate.Contains(searchValue) || m.productRequestDate.Trim().Contains(searchValue) ||
                        m.requesterName.Trim().Contains(searchValue) || m.itemName.Trim().Contains(searchValue));
                    }
    
                    //total number of rows count   
                    recordsTotal = vwReportData.Count();
                    //Paging   
                    var data = vwReportData.Skip(skip).Take(pageSize).ToList();
                    //Returning Json Data  
                    return Json(new { draw = draw, recordsFiltered = recordsTotal, recordsTotal = recordsTotal, data = data });
    
                }
                catch (Exception)
                {
                    throw;
                }
    
            }
    
      
    
            public List<string> obtainingData(List<int> Id)
            {
    
             
                List<string> data = new List<string>();
    
                ShortproductrequesterJsonTO productrequesterJson = new ShortproductrequesterJsonTO();
             
                //Insert
                for (int i = 0; i < Id.Count - 1; i++)
                {
                    var query = (from t in _context.VwReport
                                 where t.Id == Id[i]
                                 select new
                                 {
                                     id = t.Id,
                                     productRequestNo = t.productRequestNo,
                                     requesterName = t.requesterName,
                                     productName = t.productName,
                                     productRequestDate = t.productRequestDate,
                                     logDate = t.LogDate,
                                     itemName = t.itemName,
                                     lastReqStatus = t.LastReqStatus
    
                                 }).ToList();
    
    
    
    
                    foreach (var index in query)
                    {
          
    
                        productrequesterJson = new ShortproductrequesterJsonTO
                        {
                            id1 = index.id,
                            id = index.id,
                            productRequestNo = index.productRequestNo.GetValueOrDefault(),
                            requesterName = index.requesterName,
                            productName = index.productName,
                            productRequestDate = index.productRequestDate,
                            logDate = index.logDate,
                            itemName = index.itemName,
                            lastReqStatus = index.lastReqStatus
    
                        };
                        string jsonResult = JsonConvert.SerializeObject(productrequesterJson);
                        data.Add(jsonResult);
                      
                    }
                }
    
                return data;
            }
    
    
    
    
    
            public IList<string> selectedListOperation(List<int> Id, string description, string unconfirmedselectedId)
            {
               
                List<string> data = new List<string>();
                data = obtainingData(Id);
    
    
    
                Console.WriteLine("unconfirmedselectedId:" + unconfirmedselectedId);
                int lastNumber = Id.LastOrDefault();
    
    
                switch (lastNumber)
                {
                    case 1:
                        //technical review
                        runningOperationOnSelectedData(Id, description, unconfirmedselectedId, 46);
                        break;
                    case 2:
                        //confirmation
                        runningOperationOnSelectedData(Id, description, unconfirmedselectedId, 47);
                        break;
                }
    
                return data;
            }
    
            public bool runningOperationOnSelectedData(List<int> Id, string description, string unconfirmedReason, int status)
            {
                var lastchangesDate = PersianDateTime.Now.Date.ToString(format: "yyyy/MM/dd").PersianToEnglish();
                //int lastNumber = Id.LastOrDefault();
    
                int productrequesterHistoryRecordId;
    
    
    
                for (int t = 0; t < Id.Count - 1; t++)
                {
    
                    var productrequester = _context.productrequesterHistory
                   .Include(a => a.productrequester).Where(a => a.Id == a.productrequester.LastRequestStatus)
                   .FirstOrDefaultAsync(a => a.productrequesterId == Id[t]);
    
                    productrequester.Result.LastReqStatus = status;
    
    
                    if (!string.IsNullOrEmpty(unconfirmedReason))
                    {
                        
                        int unconfirmedReasonNumber = Int32.Parse(unconfirmedReason);
                        productrequesterHistoryRecordId = AccessproductrequesterHistoryDouble(productrequester.Result.productrequester.Id, lastchangesDate, productrequester.Result.SentResponseType ?? 0, unconfirmedReasonNumber, status, description).Result;
                    }
                    else
                    {
                        productrequesterHistoryRecordId = AccessproductrequesterHistoryDouble(productrequester.Result.productrequester.Id, lastchangesDate, productrequester.Result.SentResponseType ?? 0, productrequester.Result.UnconfirmedReason ?? 0, status, description).Result;
                    }
                    // Save changes in database
    
                    productrequester.Result.productrequester.LastRequestStatus = productrequesterHistoryRecordId;
                    _context.SaveChanges();
    
                }
                return true;
            }
    
    
    
            public async Task<int> AccessproductrequesterHistoryDouble(int myproductrequesterId, string lastChangesDate, int sentResponseType, int unconfirmedReason, int lastReqStatus, String desc)
            {
                var task = productrequesterHistoryLog(myproductrequesterId, lastChangesDate, sentResponseType, unconfirmedReason, lastReqStatus, desc);
                Debug.WriteLine("task:" + task);
                int result = await task;
                return await Task.FromResult(result);
    
            }
        }
    }
    
    //-------------------------------------------------------------------
    //Here is index.cshtml
    <script language="JavaScript" type="text/javascript" src="~/js/DataTable/DataTableCheckbox/dataTables.select.min.js"></script>
    <script language="JavaScript" type="text/javascript" src="~/js/datatables.min.js"></script>
    <script language="JavaScript" type="text/javascript" src="~/js/DataTable/DataTableCheckbox/dataTables.checkboxes.min.js"></script>
    
    
    <script>
        keepSelectedRows = [];
        var operationNumber = '';
        var oTable;
        var selectedIds = [];
        var descriptionText = "";
    
        var theRowObject='';
        var rowSelectedId='';
    
    
        jQuery(document).ready(function ($) {
    
    
               oTable= $('#myDummyTable').DataTable({
    
                    'orderClasses': false,
    
                    "processing": true, // for show progress bar
                    "serverSide": true, // for process server side
                    "filter": true, // this is for disable filter (search box)
                    "orderMulti": false,
    
    
                   'columnDefs': [
                       {
                           'targets': 0,
                           "searching": false,
                           'checkboxes': {
                               'selectRow': true
                             }
                        },
                            {
                                'targets': 1,
                                "searching": false,
                                "visible": false
                            }
                   ],
                    rowId: "id",
    
                    'select': {
                        'style': 'multi',
                        'selector': 'td:first-child'
                    },
                    'order': [[1, 'asc']],
    
                    "pagingType": "full_numbers",
                    //--------------------------------------------------------
                    
                "ajax": {
                    "url": "productrequesters/GetproductrequestersData",
                    "type": "POST",
                    "datatype": "json",
                },
    
    
                    { "data": "id1" },
                    { "data": "id", "name": "id", "autoWidth": true },
                    { "data": "productRequestNo", "name": "productRequestNo", "autoWidth": true },
                    { "data": "requesterName", "name": "requesterName", "autoWidth": true },
                    { "data": "productName", "name": "productName", "autoWidth": true },
                    { "data": "productRequestDate", "name": "productRequestDate", "autoWidth": true },
                    { "data": "logDate", "name": "logDate", "autoWidth": true },
                    { "data": "itemName", "name": "itemName", "autoWidth": true },
                    { "data": "lastReqStatus", "name": "lastReqStatus", "autoWidth": true },
                    {
                    defaultContent: '<input type="button" class="Edit" value="edit"/>'
                    },
                ]
        });
    
            //-----------------------------------------------------------------------------------------
    
    
                 oTable.on('click', '.Edit', function () {
    
    
                     var row = $(this).closest('tr');
                   
                     var newRow = oTable.row(row);
    
                     theRowObject = newRow;
    
    
                      $('#keepRow').val(newRow);
    
    
                     rowSelectedId = oTable.row(row).data().id;
    
    
    
                   var tempurl = '@Url.Action("AddOrEdit","productrequesters")'+'/'+ rowSelectedId;
    
                   var link = document.createElement("a");
                   link.href = tempurl
    
    
                  var url = link.protocol + "//" + link.host + link.pathname + link.search + link.hash;
        
    
                  showInPopup(url,'edit');
    
        });
    });
    
    
        function sitejsObject(myModifiedDataObject) {
            console.log('theRowObject.id:' + rowSelectedId);
    
            console.log('myModifiedDataObject.id:'+myModifiedDataObject.id);
            if (rowSelectedId == myModifiedDataObject.id) {
                oTable.row(theRowObject).data(myModifiedDataObject).draw(false);
            }
            else {
                oTable.row.add(myModifiedDataObject).draw();
            }
    
        };
    
    
    
        jQuery(document).ready(function ($) {
    
    
                $('#grantAccess,#accessDenial,#confirmation,#unconfirmation,#technicalReview').click(function () {
    
                    $("#descId").val('');
                    //$('#displaySelectList').val("0");
                    $("#modalbody").empty();
    
                    if (this.id == 'unconfirmation') {
                        $('#unconfirmedReason').prop('selectedIndex', 0);
                        $('#displaySelectList').show();
                    }
                    else {
                        $('#displaySelectList').hide();
                    }
    
                    var OTable = $("#myDummyTable").dataTable();
    
                    $("input[type=checkbox]:checked", OTable.fnGetNodes()).each(function () {
    
    
                        var row = $(this).closest('tr');
    
    
                       var newRow = oTable.row(row);
    
                        console.log("newRow:"+newRow);
     
                        keepSelectedRows.push(newRow);
        
                        selectedIds.push($(this).closest("tr").find("td:eq(1)").text());
    
                        var Id = $(this).closest("tr").find("td:eq(1)").text();
                        var productRequestNO = $(this).closest("tr").find("td:eq(2)").text();
                        var requesterName = $(this).closest("tr").find("td:eq(3)").text();
                        var productName = $(this).closest("tr").find("td:eq(4)").text();
                        var productRequestDate = $(this).closest("tr").find("td:eq(5)").text();
                        var LogDate = $(this).closest("tr").find("td:eq(6)").text();
                        var itemName = $(this).closest("tr").find("td:eq(7)").text();
                        var LastReqStatus = $(this).closest("tr").find("td:eq(8)").text();
    
                        var markup = "<tr><td>"+ Id + "</td><td>" + productRequestNO + "</td><td>" + requesterName + "</td><td>" + productName + "</td><td>" + productRequestDate + "</td><td>"  + LogDate + "</td><td>" + itemName + "</td><td>" + LastReqStatus + "</td></tr>";
    
                        $("#classTable").append(markup);
    
                    });
    
                    if (this.id == 'technicalReview') {
                   
                        selectedIds.push('001');
                    }
                    else if (this.id == 'confirmation') {
                        selectedIds.push('002');
                    }
                   
    
    
    
                    $("input[name='hiddeninput']").val(selectedIds);
    
                    if (selectedIds.length <= 1) {
                        alert("non record");
                    }
                    else {
                        $('#showDataModal').modal('show');
    
                    }
    
                });
    
            $("#deletethem").click(function () {
                if ($("input[type=checkbox]").is(':checked')) {
                    var oTable = $("#myDummyTable").dataTable();
                    $("input[type=checkbox]:checked", oTable.fnGetNodes()).each(function () {
                        $(this).prop("checked", false);
                    });
                }
            });
    
    
                });
    
        jQuery(document).ready(function ($) {
              $("#exitbutton").click(function () {
                  selectedIds = [];
    
                $('#showDataModal').modal('toggle');
              });
         });
    
        jQuery(document).ready(function ($) {
    
            var unconfirmedselectedId;
            $("#unconfirmedReason").change(function () {
    
                 unconfirmedselectedId = $('#unconfirmedReason').val();
    
                });
    
    
            $("#deletethem").click(function () {
                var OTable = $("#myDummyTable").DataTable();
                var descContent=$.trim($("#descId").val());
        $.ajax({
            url: "productrequesters/selectedListOperation",
            type: "POST",
            async: true,
            cache: false,                  /*descriptionText*/
            data: { "Id": selectedIds, "description": descContent, "unconfirmedselectedId": unconfirmedselectedId },
            success: function (data) {
    
                $.each(data, function (index, value) {
                   //here is where the error occurs.
                    OTable.row(keepSelectedRows.pop()).data(data).draw(false);
    
                });
    
            }
        });
      });
    });
    
    </script>
    
    @*************************************@
    <div class="my-5 col-sm-12 p-4">
    
        <table id="myDummyTable" class="table m-table mytable table-striped table-bordered mb-4" style="width: auto;">
            <thead>
                <tr id="headerrow">
                    <th>
                        <input type='checkbox'>
                    </th>
                    <th hidden>
                        ID
                    </th>
                    <th>
                        request number
                    </th>
                    <th>
                        requester
                    </th>
                    <th>
                        product
                    </th>
                    <th>
                        request date
                    </th>
                    <th>
                        last change date
                    </th>
                    <th>
                        item
                    </th>
                    <th>
                        last status
                    </th>
                    <th>
                        operation
                    </th>
                </tr>
            </thead>
            <tbody>
            </tbody>
        </table>
    </div>
    
    <div class="row">
        <div class="col-12 d-flex justify-content-center" style="padding: 23px;">
            <input class="btn" id="technicalReview" type="button" value="technical review" data-whatever="technicalReview" style="margin: 0 0.5em;" />
            <input class="btn" id="confirmation" type="button" value="Confirmation" data-whatever="confirmation" style="margin-left: 0.5rem;" />
           
        </div>
    </div>
    
    
    
    @*******************************************************************************************@
    <div class="modal fade" id="showDataModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
        <div class="modal-dialog modal-dialog-centered modal-dialog-scrollable" role="document">
            <div class="modal-content" style="overflow:auto;">
                <div class="modal-header">
                    <h4>Do you agree to change the status?</h4>
                </div>
                <form method="post">
    
                    <div class="row border-light input-group mt-4 mr-1">
                        <div class="form-group col-12" id="displaySelectList" style="display:none;">
                            @Html.ValidationMessage("unconfirmedReason", "type:", new { @class = "d-inline-block col-3 p-0" })
                            @Html.DropDownList("unconfirmedReason", new SelectList((IEnumerable<SelectListItem>)ViewData["unconfirmedReason"], "Value", "Text"), "select", new { @class = "form-control d-inline-block col-5", id = "unconfirmedReason", style = "left: 2rem" })
                        </div>
                    </div>
    
                    <div class="modal-body pt-0">
                      
                        <input type="hidden" name="hiddenInput" />
                        <div id="result" class="">
    
                            <table id="classTable" class="table table-bordered" border="1">
                                <thead>
                                    <tr id="headerrow">
                                        <th>
                                            request number
                                        </th>
                                        <th>
                                            Requester
                                        </th>
                                        <th>
                                            product
                                        </th>
                                        <th>
                                            request date
                                        </th>
                                        <th>
                                            last change date
                                        </th>
                                        <th>
                                            product
                                        </th>
                                        <th>
                                            last status
                                        </th>
                                    </tr>
                                </thead>
                                <tbody id="modalbody">
                                </tbody>
    
                            </table>
                        </div>
    
                    </div>
    
                    <div class="form-group col-10 mt-4">
                        <label class="control-label" for="descId">explantaion</label>
                        <textarea class="form-control input-xlarge" placeholder="explanation" id="descId" rows="3"></textarea>
                    </div>
    
                    <div class="modal-footer mt-4">
                     
                        <button type="button" id="deletethem" class="btn btn-info" data-dismiss="modal">confirm</button>
             
                    </div>
                </form>
            </div>
        </div>
    </div>
    
    
    
    
    @section scripts{
    
        <script>
    
    
        $('#request_layout').css({ "background-color": "rgb(50, 149, 155)" });
        </script>
    }
    
    //------------------------------------------------------------
    public class ShortproductrequesterJsonTO
        {
            public int id1 { get; set; }
            public int id { get; set; }
            public string productRequestDate { get; set; }
            public int productRequestNo { get; set; }
            public string productName { get; set; }
            public string requesterName { get; set; }
            public string itemName { get; set; }
            public string logDate { get; set; }
            public string lastReqStatus { get; set; }
    
        }
    I appreciate if anyone suggests me how can I solve the error.

    </div> </div>

    Sunday, February 28, 2021 2:09 PM

All replies

  • User1312693872 posted

    Hi,Elenorarez

    Is your error occurred when you click the edit and show the data rows in a modal?

    The problem could be caused when the columns defined is more than the headers in the table in the modal:

    https://datatables.net/manual/tech-notes/4

    Your table have seven headers while your post eight columns to it.

    <thead>
        <tr id="headerrow">
           <th>
              request number
           </th>
           <th>
              Requester
           </th>
    @*..seven headers..*@ </tr> </thead>
    var markup = "<tr><td>"+ Id + "</td><td>" + productRequestNO + "</td><td>" + requesterName + "</td><td>" + productName + "</td><td>" + productRequestDate + "</td><td>"  + LogDate + "</td><td>" + itemName + "</td><td>" + LastReqStatus + "</td></tr>"; //eight colums

    Best Regards,

    Jerry Cai

    Monday, March 1, 2021 9:37 AM
  • User-259252065 posted

    Hi. thanks for your answer. The modal works correct. The problem is when the rows in the datatable is going to be updated.

    Monday, March 1, 2021 9:47 AM
  • User-259252065 posted

    Each row has an edit button, and by clicking it, a modal pops up to the user and after modifying the data fields, and by clicking save button, it edits the data in the that row. I used the mentioned function for it as well which works correctly. but after choosing multiple data to update, it doesn't work. I think I have to send the array of data in Json type. when I click the edit button to edit just one row I send the data object in json format to ajax call and it works fine. But I don't know how to send the array of data in json format to ajax call.

    //-------------------------------------------------------------------- for editing a row by clicking the edit buttun that each row has I used somethink like the following and it works correctly: //---------------------------------------------------------------

    public async Task<IActionResult> AddOrEdit(int id, productrequesterViewModel productrequesterviewmodel)
     {
    
    new ShortproductrequesterJsonTO productrequesterJson = new ShortproductrequesterJsonTO
                        {
                            id1 = index.id,
                            id = index.id,
                            productRequestNo = index.productRequestNo.GetValueOrDefault(),
                            requesterName = index.requesterName,
                            productName = index.productName,
                            productRequestDate = index.productRequestDate,
                            logDate = index.logDate,
                            itemName = index.itemName,
                            lastReqStatus = index.lastReqStatus
    
                        };
    
    return Json(productrequesterJson);
    }

    Monday, March 1, 2021 9:50 AM
  • User1312693872 posted

    Hi,Elenorarez

    If you post multiple checkboxes, you should use List to accept them, set a breakpoint to check whether you can get the

    productrequesterviewmodel.

    This is a sample to pass the checked boxed to controller:

                            //..
                                <tbody>
                                    @foreach (ShortproductrequesterJsonTO SHORT in Model)
                                    {
                                    <tr>
                                        <td><input type="checkbox" id="check1" class="chkclass" value="@SHORT.id" /></td>
                                        <td>@SHORT.id1</td>
                                        <td>@SHORT.productName</td>
                                        <td>@SHORT.productRequestNo</td>
                                    </tr>
                                    }
                                </tbody>
    //.. <button type="button" id="button1" class="btn btn-info">confirm</button> @section Scripts { <script> $("#button1").click(function () { var products = new Array(); $('input:checked').each(function () { var product = {}; product.id = parseInt($(this).closest("tr").find("input").val()); //id for checkbox product.id1 = parseInt($(this).closest("tr").find("td:eq(1)").text().trim()); //id product.productName = $(this).closest("tr").find("td:eq(2)").text().trim(); product.productRequestNo = $(this).closest("tr").find("td:eq(3)").text().trim(); products.push(product); }); $.ajax({ type: "POST", url: "/Home/AddOrEdit", data: { shortproduct: products}, success: function (re) { } }); }); </script> }
    [HttpPost]
    public async Task<IActionResult> AddOrEdit(List<ShortproductrequesterJsonTO> shortproduct)

    Best Regards,

    Jerry Cai

    Tuesday, March 2, 2021 5:52 AM