Xử lý lỗi sắp xếp và lọc thời gian trong DataTable với C# MVC

Nguyên nhân và cách khắc phục lỗi sắp xếp cột Time không theo thứ tự giảm dần

Lỗi xuất phát từ việc sử dụng chuỗi đã định dạng thay vì giá trị timestamp gốc để sắp xếp dữ liệu trong DataTable. Dưới đây là giải pháp:


"columns": [
    // Các cấu hình cột khác giữ nguyên...
    {
        data: "Time", // Dữ liệu gốc (giả sử ở dạng "/Date(1728380400000)/")
        render: function (data, type, row) {
            if (!data) {
                return type === "display" ? "NULL" : "";
            }
            const timeValue = parseInt(data.substr(6)); 
            if (type === "sort" || type === "filter") {
                return timeValue; // Sử dụng cho sắp xếp và lọc
            } else { 
                const formattedDate = new Date(timeValue);
                return formattedDate.toLocaleDateString() + ' ' + formattedDate.toLocaleTimeString();
            }
        }
    }
]

Khi type === "sort", hàm trả về giá trị số timestamp giúp sắp xếp chính xác mà không phụ thuộc vào so sánh chuỗi.

Những vấn đề và cách sửa lỗi lọc thời gian bắt đầu/kết thúc

Tình trạng hiện tại không hoạt động do sai sót khi xử lý định dạng ngày tháng giữa các hệ thống ngôn ngữ khác nhau. Giải pháp cải tiến như sau:


$.fn.dataTable.ext.search.push(
    function (settings, data, dataIndex) {
        const processDropdown = document.getElementById("StepId");
        const selectedProcess = processDropdown.options[processDropdown.selectedIndex].text;
        const currentProcess = data[0] || ""; 
        const isProcessMatched = selectedProcess === "--Chọn công đoạn--" || currentProcess === selectedProcess;

        let startTime = $('#min').val() ? new Date($('#min').val()).getTime() : NaN;
        let endTime = $('#max').val() ? new Date($('#max').val()).getTime() : NaN;
        
        const rowData = settings.aoData[dataIndex]._aFilterData[orderIndex]; // orderIndex=6
        const rowTimestamp = rowData ? parseInt(rowData) : NaN;

        if (!isNaN(startTime) && !isNaN(endTime) && startTime > endTime) {
            errorMessage.textContent = 'Thời gian kết thúc phải sau thời gian bắt đầu.';
            return false;
        } else {
            errorMessage.textContent = '';
        }

        const isTimeValid = (isNaN(startTime) && isNaN(endTime)) || 
                            (isNaN(startTime) && rowTimestamp <= endTime) || 
                            (startTime <= rowTimestamp && isNaN(endTime)) || 
                            (startTime <= rowTimestamp && rowTimestamp <= endTime);

        return isProcessMatched && isTimeValid;
    }
);

Với cách này, tất cả các phép so sánh đều dựa trên giá trị số của timestamp, loại bỏ rủi ro liên quan đến định dạng ngày tháng khác biệt giữa các hệ thống.

Thẻ: DataTable C# MVC

Đăng vào ngày 5 tháng 7 lúc 05:25