对于上下文: 我有一个使用DataTables的应用程序,它使用默认的搜索功能,并且工作得很好.但是,还有其他筛选器和权限限制来定义页面上显示的内容.我收到用户的投诉,当他们找不到现有的商品时,他们想知道为什么.

That being said, I can easily create a custom message when zero results are found. However I have no idea how I can pass it back to the DataTable so it can be displayed.

下面共享的代码使用处理程序来获取数据.在本例中,我将自定义消息添加为一个字段并将其隐藏在屏幕上.但是,这显然不起作用,因为当没有记录时,没有记录显示:)..

以下是我的处理程序和ASPX页面的代码.更多的是供参考,因为我知道这个策略不会奏效.

如有任何 idea ,我们将不胜感激!

Public Sub ProcessRequest(context As HttpContext) Implements IHttpHandler.ProcessRequest
    Dim displayLength As Integer = Integer.Parse(context.Request("iDisplayLength"))
    Dim displayStart As Integer = Integer.Parse(context.Request("iDisplayStart"))
    Dim sortCol As Integer = Integer.Parse(context.Request("iSortCol_0"))
    Dim sortDir As String = context.Request("sSortDir_0")
    Dim search As String = context.Request("sSearch")

    Dim Name As String = context.Server.HtmlEncode(context.Request.Cookies("User_Profile")("User_Name"))
    Dim User_Name As String = FindName(Name)
    Dim User_Id As String = FindId(Name)
    Dim Area As String = context.Server.HtmlEncode(context.Request.Cookies("User_Profile")("Default_Area"))
    Dim Dept As String = ""
    Dim Status As String = ""
    Dim ViewMyWOs As String = "All"
    Try
        ViewMyWOs = context.Server.HtmlEncode(context.Request.Cookies("WOInfo")("SaveMyWO"))
    Catch ex As Exception
    End Try
    Try
        If Not context.Request.Cookies("userInfo") Is Nothing Then
            Dept = _
                 context.Server.HtmlEncode(context.Request.Cookies("userInfo")("SaveDeptQuery"))
            Status = _
                 context.Server.HtmlEncode(context.Request.Cookies("userInfo")("SaveStatusQuery"))
        End If
    Catch ex As Exception

    End Try
    Dim spName As String = "spGetWORKORDER"

    Dim cs As String = ConfigurationManager.ConnectionStrings("WorkOrdersConString").ConnectionString
    Dim listWOs As New List(Of WorkOrder)()
    Dim filteredCount As Integer = 0
    Using con As New SqlConnection(cs)
        Dim cmd As New SqlCommand(spName, con)
        cmd.CommandType = CommandType.StoredProcedure
        cmd.Parameters.AddWithValue("@DisplayLength", displayLength)
        cmd.Parameters.AddWithValue("@DisplayStart", displayStart)
        cmd.Parameters.AddWithValue("@SortCol", sortCol)
        cmd.Parameters.AddWithValue("@SortDir", sortDir)
        cmd.Parameters.AddWithValue("@Search", If(String.IsNullOrEmpty(search), Nothing, search))
        cmd.Parameters.AddWithValue("@Area", Area)
        cmd.Parameters.AddWithValue("@Dept", If((Dept = "All Departments"), Nothing, Dept))
        cmd.Parameters.AddWithValue("@Status", Status)
        cmd.Parameters.AddWithValue("@User_Name", User_Name)
        cmd.Parameters.AddWithValue("@User_Id", User_Id)
        cmd.Parameters.AddWithValue("@ViewMyWOs", ViewMyWOs)
        con.Open()
        Dim rdr As SqlDataReader = cmd.ExecuteReader()
        While rdr.Read()
            Dim workOrder As New WorkOrder()
            workOrder.WO_Id = Convert.ToInt32(rdr("WO_Id"))
            workOrder.Priority = rdr("Priority").ToString()
            workOrder.Date_Submitted = Convert.ToDateTime(rdr("Date_Submitted")).ToShortDateString
            workOrder.Submitted_By = rdr("Submitted_By").ToString()
            workOrder.Task = rdr("Task").ToString()
            workOrder.Material = rdr("Material").ToString()
            workOrder.ChargeNumber = rdr("ChargeNumber").ToString()
            workOrder.Summary = rdr("Summary").ToString()
            workOrder.Part_Number = rdr("Part_Number").ToString()
            workOrder.QTY = rdr("QTY").ToString()
            workOrder.Department = rdr("Department").ToString()
            workOrder.Machine = rdr("Machine").ToString()
            workOrder.Full_Name = rdr("Full_Name").ToString()
            workOrder.Status = rdr("Status").ToString()
            workOrder.Requested_Completion = Convert.ToDateTime(rdr("Requested_Completion")).ToShortDateString
            workOrder.Completion_Date = rdr("Completion_Date").ToString()
            If workOrder.Completion_Date <> "" Then
                workOrder.Completion_Date = Convert.ToDateTime(workOrder.Completion_Date).ToShortDateString
            End If

            workOrder.Late = DateTime.Compare(Convert.ToDateTime(workOrder.Requested_Completion), DateTime.Now.AddDays(-1))
            filteredCount = Convert.ToInt32(rdr("TotalCount"))
            Dim message As String = "No matching records found"
            If filteredCount = 0 Then
                'Modify message based on the reason for no results
                message = "I like to Party"
            End If
            workOrder.Message = message
            listWOs.Add(workOrder)
        End While
    End Using

    Dim result = New With { _
        Key .iTotalRecords = GetTotalCount(), _
        Key .iTotalDisplayRecords = filteredCount, _
        Key .aaData = listWOs _
    }


    Dim js As New JavaScriptSerializer()
    context.Response.Write(js.Serialize(result))
End Sub

和ASPX页面

$(document).ready(function () {
                var table = $('#npwoList').dataTable({
                    dom: 'Bfrtip',
                    columns: [
                        { 'data': 'WO_Id' },
                        { 'data': 'Priority' },
                        { 'data': 'Date_Submitted' },
                        { 'data': 'Submitted_By' },
                        { 'data': 'Task' },
                        { 'data': 'Material' },
                        { 'data': 'ChargeNumber' },
                        { 'data': 'Summary' },
                        { 'data': 'Part_Number' },
                        { 'data': 'QTY' },
                        { 'data': 'Department' },
                        { 'data': 'Machine' },
                        { 'data': 'Full_Name' },
                        { 'data': 'Status' },
                        { 'data': 'Requested_Completion' },
                        { 'data': 'Completion_Date' },
                        { 'data': 'Late' },
                        { 'data': 'Message' }
                    ],
                    columnDefs:
                        [
                            { //these columns are always visible
                                "targets": [0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15],  
                                "visible": true,
                                "orderable": true,
                                "sortable": true,
                                "searchable": true,
                            },
                            {  //these columns are always invisible
                                "targets": [16,17],
                                "visible": false,
                                "orderable": false,
                                "sortable": false,
                                "searchable": false
                            }
                        ],                        
                    bServerSide: true,
                    sAjaxSource: 'Handlers/WODataHandler.ashx',
                    deferRender: true,
                    lengthMenu: [
                    [25, 50, 100, 1000],
                    ['25 rows', '50 rows', '100 rows', 'Show all']
                    ],
                    buttons: ['pageLength',
                         {
                             extend: 'colvis',
                             collectionLayout: 'fixed two-column',
                             postfixButtons: ['colvisRestore']
                         }
                    ],
                    language: {
                        buttons: {
                            colvis: 'Hide/Show Columns'                                
                        },                            
                        zeroRecords: **Add Message Here!!**//$('#npwoList tbody tr:eq(2) td:eq(17)').text()
                    },
                    "scrolly": 400,
                    "stateSave": true,
                    "order": [[0, "desc"]],
                    "stateSaveParams": function (settings, data) {
                        data.start = 0;
                    },

                    fnRowCallback: function (row, data, displayIndex) {
                        var api = this.api();
                        if ($(api.cell(displayIndex, 13).node()).text() == 'In-Process' &&
                                $(api.cell(displayIndex, 16).node()).text() > 0) {
                            $(row).addClass('green');
                        }
                        if ($(api.cell(displayIndex, 13).node()).text() != 'Complete' &&
                                $(api.cell(displayIndex, 13).node()).text() == 'Waiting - Engineering' &&
                                    $(api.cell(displayIndex, 16).node()).text() >= 0){
                            $(row).addClass('blue');
                        }
                        if ($(api.cell(displayIndex, 13).node()).text() != 'Complete' &&
                                $(api.cell(displayIndex, 16).node()).text() < 0) {
                            $(row).addClass('red');
                        }
                        if ($(api.cell(displayIndex, 13).node()).text() != 'Complete' &&
                                $(api.cell(displayIndex, 13).node()).text() != 'In-Process' &&
                                $(api.cell(displayIndex, 16).node()).text() > 0) {
                            $(row).addClass('black');
                        }
                        if ($(api.cell(displayIndex, 13).node()).text() != 'Complete' &&
                                $(api.cell(displayIndex, 13).node()).text() == 'Monitor') {
                            $(row).addClass('blue');
                        }                            
                    }
                });
                $('#npwoList tbody').on('click', 'tr', function () {
                    var id = $('td', this).eq(0).text();
                    document.getElementById('<%=txtWorkOrderId.ClientID%>').value = id;
                    var clickButton = document.getElementById("<%= btnOpenNPWO.ClientID%>");
                    clickButton.click();
                });
            });               

推荐答案

好的,这里的解决方案很简单.

步骤1-向JSON响应中添加一个参数,这将返回一个值,而不管检索到的记录数量是多少.在本例中,我添加了iMessage.

Dim result = New With {
        Key .iTotalRecords = GetTotalCount(),
        Key .iTotalDisplayRecords = filteredCount,
        Key .imessage = message,
        Key .aaData = listWOs
    }

要在客户端使用它,您需要将"zeroRecords"变量更改为函数.

language: {
    zeroRecords: function () {
        return function () {
            return $('#npwoList').DataTable().ajax.json().imessage;
        };
     }
 },

Asp.net相关问答推荐

Swashbuckle 通过 .NET 应用程序中的 XML 注释使用格式标识符

在 Web.Config 中模拟标签

我们可以在一个网页中使用多个表单吗?

任何人都有解决 Internet Explorer 上剩余 n 项问题的 idea 吗?

指定的 CGI 应用程序遇到错误,服务器终止了进程

'Access-Control-Allow-Origin' 标头包含多个值 '*, *',但只允许一个

你如何确定哪个验证器失败了?

您对 Windows Workflow Foundation 有何体验?

asp.net cookie、身份验证和会话超时

最佳服务器端 .NET PDF 编辑库

如何使用 asp.net 获取 html Select 的选定值

带有 ASP.NET WebMethod 的 Jquery AJAX 返回整个页面

您正在使用哪些身份验证和授权方案 - 为什么?

如何在 ASP.NET MVC 中设置时区?

如何获取程序集的最后修改日期?

ASP.NET 应用程序状态与静态对象

如何使用 encodeURIComponent() 解码在 JS 中编码的 HTML?

ASP.NET:在 Response.Redirect(...) 之后代码会发生什么?

如何修复 ASP.NET 错误文件 'nnn.aspx' 尚未预编译,无法请求.?

如何使用 int ID 列更改 ASP.net Identity 2.0 的表名?