日期更改后重新加载 Ajax 数据表

问题描述 投票:0回答:1

我正在我的 asp.net MVC 项目上创建一个预订仪表板。在这里,我为主视图提供了日期时间选择器,并从脚本中将当前日期分配给文档就绪函数上的日期时间选择器。

然后它通过 Ajax 数据表将当前日期传递给 ajax 返回数据,将其分配给表并显示数据。

这里我在部分视图上添加了表格。我将此表添加到部分视图的原因是当有任何更改时重新加载部分视图。

这是我的 HTML 视图代码

<div class="container-xxl flex-grow-1 container-p-y">
  <div class="row">
    <div class="col-md-12 col-sm-12 col-xs-12">
      <div class="card mb-4">
        <div class="card-body">
          <div class="date-container">
            <input type="date" id="bookingDate" name="bookingDate" />
          </div>
        </div>
      </div>
    </div>
  </div>
  <div class="row">
    <div class="col-md-12 col-sm-12 col-xs-12"> 
    @{ Html.RenderPartial("_ArrivingSection"); } </div>
  </div>
  <div class="row">
    <div class="col-md-6 col-sm-6 col-xs-6"> 
    @{ Html.RenderPartial("_InProcessJobsSection"); } </div>
    <div class="col-md-6 col-sm-6 col-xs-6"> 
    @{ Html.RenderPartial("_FutureBookingsSection"); } </div>
  </div>

这是当前的工作脚本,从控制器获取数据并显示在表格上。

 $('#arriving').DataTable({
    processing: true,
    serverSide: true,
    filter: true,
    scrollY: '200px', // Set the fixed height for the table
    orderMulti: false,
    ajax: {
       url: '@Url.Action("GetArrivingInformations", "Booking")',
       type: "POST",
       datatype: "json",
    },
    columns: [{
          "data": "CustomerName",
          "name": "Customer Name"
       },
       {
          "data": "ContactNumber",
          "name": "Contact Number"
       },
       {
          "data": "ServiceName",
          "name": "Service"
       },
       {
          "data": "CheckInTime",
          "name": "Check In",
          "render": function (data, type, row) {
             // Assuming data is a TimeSpan object with Hours and Minutes
             if (data) {
                // Convert the TimeSpan to a valid time in Date format
                let hours = data.Hours;
                let minutes = data.Minutes;

                // Create a Date object with the current date but set the time to the TimeSpan's hours and minutes
                let date = new Date();
                date.setHours(hours, minutes);

                // Format the date to AM/PM
                return date.toLocaleTimeString([], {
                   hour: '2-digit',
                   minute: '2-digit',
                   hour12: true
                });
             }
             return 'Invalid Time';
          }
       },
       {
          "data": "EncryID",
          "render": function (data, type, row) {
             // Check if customer has already arrived
             if (row.IsCustomerArrived) {
                // If arrived, don't display the 'Arrived' button
                return `<div class="btn-group bx-pull-right" role="group">
                     <a href="#" class="btn-info btn-sm common-btn" onclick="openAssignJobModal('${data}', '${row.ServiceName}','${row.CustomerName}')">Assign Job</a>&nbsp;&nbsp;

                 </div>`;
             } else {
                // Display the 'Arrived' button if the customer hasn't arrived
                return `<div class="btn-group bx-pull-right" role="group">
                     <a href="#" class="btn-primary btn-sm common-btn" onclick="markAsArrived('${data}', this)">Arrived</a>&nbsp;&nbsp;
                    <a href="#" class="btn-info btn-sm common-btn" onclick="openAssignJobModal('${data}', '${row.ServiceName}')">Assign Job</a>&nbsp;&nbsp;

                 </div>`;
             }
          }
       }
    ],
    language: {
       search: "Search"
    }
 });

我想在日期更改时执行相同的操作,然后将日期传递给控制器并获取数据并重新加载表格

这是我尝试过的,但它不起作用,我的数据表脚本有很多错误。当我将获取数据添加到文档准备功能时,它会出现诸如数据表未定义、数据表未加载之类的错误。有人可以帮助我用这种方式或任何替代方式完成这个过程吗?

<script src="~/Addons/DataTable/jquery-3.6.1.min.js"></script>
<!-- DataTables -->
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.11.5/css/jquery.dataTables.css">
<script type="text/javascript" charset="utf8" src="https://cdn.datatables.net/1.11.5/js/jquery.dataTables.js"></script>

< script >

    var arrivingTable; // Declare this globally so we can access it from the date change function

$(document).ready(function () {

    // Function to safely reload the table
    function safeReloadTable() {
        arrivingTable.ajax.reload();
    }

    // Bind date change event
    $('#bookingDate').on('change', function () {
        console.log('Date changed:', $(this).val());
        safeReloadTable();
    });
    // Set current date in the date picker
    const today = new Date().toISOString().split('T')[0];
    $('#bookingDate').val(today);

    try {
        arrivingTable = $('#arriving').DataTable({
            processing: true,
            serverSide: true,
            filter: true,
            scrollY: '200px',
            orderMulti: false,
            ajax: {
                url: '@Url.Action("GetArrivingInformations", "Booking")',
                type: "POST",
                datatype: "json",
                data: function (d) {
                    return $.extend({}, d, {
                        "bookingDate": $('#bookingDate').val()
                    });
                }
            },
            columns: [
                // Your existing columns configuration
                {
                    "data": "CustomerName",
                    "name": "Customer Name"
                },
                {
                    "data": "ContactNumber",
                    "name": "Contact Number"
                },
                {
                    "data": "ServiceName",
                    "name": "Service"
                },
                {
                    "data": "CheckInTime",
                    "name": "Check In",
                    "render": function (data, type, row) {
                        if (data) {
                            let hours = data.Hours;
                            let minutes = data.Minutes;
                            let date = new Date();
                            date.setHours(hours, minutes);
                            return date.toLocaleTimeString([], {
                                hour: '2-digit',
                                minute: '2-digit',
                                hour12: true
                            });
                        }
                        return 'Invalid Time';
                    }
                },
                {
                    "data": "EncryID",
                    "render": function (data, type, row) {
                        if (row.IsCustomerArrived) {
                            return `<div class="btn-group bx-pull-right" role="group">
                                <a href="#" class="btn-info btn-sm common-btn" onclick="openAssignJobModal('${data}', '${row.ServiceName}','${row.CustomerName}')">Assign Job</a>
                            </div>`;
                        } else {
                            return `<div class="btn-group bx-pull-right" role="group">
                                <a href="#" class="btn-primary btn-sm common-btn" onclick="markAsArrived('${data}', this)">Arrived</a>
                                <a href="#" class="btn-info btn-sm common-btn" onclick="openAssignJobModal('${data}', '${row.ServiceName}','${row.CustomerName}')">Assign Job</a>
                            </div>`;
                        }
                    }
                }
            ]
        });

    } catch (error) {
        console.error('Error initializing DataTable:', error);
    }
});

</script>

javascript c# html jquery asp.net-mvc
1个回答
0
投票

该错误告诉您

DataTable
未定义。这就是您联系它的方式:

arrivingTable = $('#arriving').DataTable({
    //...
});

导致此问题的原因可能有多种。因此,您需要仔细检查此清单才能解决问题:

  • 通过研究开发工具中的结构来验证 jquery 是否在生成的页面中。我知道您相信它的存在,但您需要仔细检查
  • 使用浏览器开发工具验证 DataTable 是否包含在内
  • 验证 jquery 和 DataTable 是否都包含在您的页面中一次
  • 验证 DataTable 的脚本位于结构中的 jquery 脚本之后
  • 确保您对
  • .DataTable()
     的调用发生在 
    after both jquery 和 DataTable 库已完全加载,可能会将其放入文档加载/就绪事件中(看来您已经这样做了,但请仔细检查) )
  • 当您调用
  • arrivingTable
     时,请确保 
    DataTable
    已存在于您的结构中
如需进一步建议,您需要分享有关您看到的错误的更多详细信息。

© www.soinside.com 2019 - 2024. All rights reserved.