简体   繁体   English

使用C#服务器端处理对DataTables Tble进行列过滤

[英]ColumnFiltering a DataTables tble using c# server side processing

Ok, I have a table which is populated using DataTables server side functionality. 好的,我有一个使用DataTables服务器端功能填充的表。 I have also added the .ColumnFilter plugin to search on individual columns. 我还添加了.ColumnFilter插件来搜索各个列。 My problem is, is that the main global search works fine, but the individual one doesnt do anything. 我的问题是,主要的全局搜索工作正常,但是单个搜索却什么也没做。

The DataTables config is as such DataTables配置就是这样

var getUserNames = function () {
$("#tbl").dataTable({
        "oLanguage": {
            "sZeroRecords": "No records to display",
            "sSearch": "Search on UserName"
        },
        "sDom": "<'row-fluid'<'span6'T><'span6'f>r>t<'row-fluid'<'span6'i><'span6'p>>",
        "oTableTools": {
            "sSwfPath": "media/swf/copy_csv_xls_pdf.swf",
            "aButtons": [
            "copy",
            "print",
            {
                "sExtends": "collection",
                "sButtonText": 'Save <span class="caret" />',
                "aButtons": ["csv", "xls", "pdf"]
            }
            ]
        },

        "aLengthMenu": [[25, 50, 100, 150, 250, 500, -1], [25, 50, 100, 150, 250, 500, "All"]],
        "iDisplayLength": 20,
        "bSortClasses": false,
        "bStateSave": false,
        "bPaginate": true,
        "bAutoWidth": false,
        "bProcessing": true,
        "bServerSide": true,
        "bDestroy": true,
        "sAjaxSource": "WebService1.asmx/GetItems",
        "bJQueryUI": true,
        "sPaginationType": "full_numbers",
        "bDeferRender": true,
        "fnServerParams": function (aoData) {
             aoData.push({ "name": "iParticipant", "value": $("#participant").val
          (), "name": "iArchiveYears", "value": $("#ArchiveYears option:selected").text() });
        },

        "fnServerData": function (sSource, aoData, fnCallback) {
            $.ajax({
                "dataType": 'json',
                "contentType": "application/json; charset=utf-8",
                "type": "GET",
                "url": sSource,
                "data": aoData,
                "success":
                            function (msg) {

                                var json = jQuery.parseJSON(msg.d);
                                fnCallback(json);
                                $("#tbl").show();
                            }
            });
        }
    })
    .columnFilter({

        aoColumns: [
            { type: "text" },
            { type: "text" }
         ]
    });

}

with this as my Webservice: 以此作为我的Web服务:

using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Web.Script.Services;
using System.Text;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
using System.Web.Configuration;

/// <summary>
/// Summary description for WebService1
/// </summary>
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line. 
[System.Web.Script.Services.ScriptService]
public class WebService1 : System.Web.Services.WebService {

    public WebService1 () {

        //Uncomment the following line if using designed components 
        //InitializeComponent(); 
    }


    [WebMethod]
    [ScriptMethod(UseHttpGet = true)]

    public string GetItems()
    {
        int sEcho = ToInt(HttpContext.Current.Request.Params["sEcho"]);
        int iDisplayLength = ToInt(HttpContext.Current.Request.Params["iDisplayLength"]);
        int iDisplayStart = ToInt(HttpContext.Current.Request.Params["iDisplayStart"]);
        string rawSearch = HttpContext.Current.Request.Params["sSearch"];

        string participant = HttpContext.Current.Request.Params["iParticipant"];

        string archiveYears = HttpContext.Current.Request.Params["iArchiveYears"];

        DateTime year =  DateTime.Now;

        if (archiveYears == null)
        {
            archiveYears = year.Year.ToString();
        }

        var sb = new StringBuilder();

        var whereClause = string.Empty;
        if (participant.Length > 0)
        {
            sb.Append(" Where participant = ");
            sb.Append("'" + participant + "'");
            sb.Append(" AND Year(MsgDate)= ");
            sb.Append("'" + archiveYears + "'");

            whereClause = sb.ToString();
        }
        sb.Clear();

        var filteredWhere = string.Empty;

        var wrappedSearch = "'%" + rawSearch + "%'";

        if (rawSearch.Length > 0)
        { 
            sb.Append(" WHERE Participant LIKE ");
            sb.Append(wrappedSearch);
            sb.Append(" OR MsgDate LIKE ");

            sb.Append(wrappedSearch);                                  

            filteredWhere = sb.ToString();
        }


        //ORDERING

        sb.Clear();

        //Check which column is to be sorted by in which direction     
        for (int i = 0; i < 11; i++)
        {
            if (HttpContext.Current.Request.Params["bSortable_" + i] == "true")
            {
                sb.Append(HttpContext.Current.Request.Params["iSortCol_" + i]);
                sb.Append(" ");
                sb.Append(HttpContext.Current.Request.Params["sSortDir_" + i]);
            }
        }
        orderByClause = sb.ToString();

        if (!String.IsNullOrEmpty(orderByClause))

            orderByClause = orderByClause.Replace("0", ", Participant ");
            orderByClause = orderByClause.Replace("2", ", MsgDate ");
            orderByClause = orderByClause.Remove(0, 1);

        }
        else
        {
            orderByClause = "MsgDate ASC";
        }
        orderByClause = "ORDER BY " + orderByClause;

        sb.Clear();

        var numberOfRowsToReturn = "";
        numberOfRowsToReturn = iDisplayLength == -1 ? "TotalRows" : (iDisplayStart + iDisplayLength).ToString();


        string query = @" 
                        declare @MA TABLE(  Participant VARCHAR(50), MsgDate DateTime))
                        INSERT
                        INTO
                            @MA ( Participant, MsgDate
                                FROM [MsgDateDetail] 
                                {4}                   

                        SELECT *
                        FROM
                            (SELECT row_number() OVER ({0}) AS RowNumber
                                  , *
                             FROM
                                 (SELECT (SELECT count([@MA].Participant)
                                          FROM
                                              @MA) AS TotalRows
                                       , ( SELECT   count( [@MA].Participant) FROM @MA {1}) AS TotalDisplayRows            
                                       ,[@MA].Participant
                                       [@MA].MsgDate

                                  FROM
                                      @MA {1}) RawResults) Results
                        WHERE
                            RowNumber BETWEEN {2} AND {3}";


        query = String.Format(query, orderByClause, filteredWhere, iDisplayStart + 1, numberOfRowsToReturn, whereClause);

        SqlConnection conn = new SqlConnection(WebConfigurationManager.ConnectionStrings["MIReporting"].ConnectionString);

        try
        {
            conn.Open();
        }
        catch(Exception e )
        {
            Console.WriteLine(e.ToString());
        }

        var DB=new SqlCommand();
        DB.Connection=conn;
        DB.CommandText=query;
        var  data = DB.ExecuteReader();

        var totalDisplayRecords = "";
        var totalRecords = "";
        string outputJson = string.Empty;

        var rowClass = "";
        var count = 0;

        while(data.Read())
        {

            if (totalRecords.Length ==0)
            {
                totalRecords = data["TotalRows"].ToString();
                totalDisplayRecords = data["TotalDisplayRows"].ToString();
            }
            sb.Append("{");
            sb.AppendFormat(@"""DT_RowId"": ""{0}""", count++);
            sb.Append(",");
            sb.AppendFormat(@"""DT_RowClass"": ""{0}""", rowClass);
            sb.Append(",");
            sb.AppendFormat(@"""0"": ""{0}""", data["Participant"]);
            sb.Append(",");
            sb.AppendFormat(@"""2"": ""{0}""", data["MsgDate"]).Replace("\t", String.Empty);


            sb.Append("},");
        }

        // handles zero records
        if (totalRecords.Length == 0)
        {
            sb.Append("{");
            sb.Append(@"""sEcho"": ");
            sb.AppendFormat(@"""{0}""", sEcho);
            sb.Append(",");
            sb.Append(@"""iTotalRecords"": 0");
            sb.Append(",");
            sb.Append(@"""iTotalDisplayRecords"": 0");
            sb.Append(", ");
            sb.Append(@"""aaData"": [ ");
            sb.Append("]}");
            outputJson = sb.ToString();

            return outputJson;
        }
        outputJson = sb.Remove(sb.Length - 1, 1).ToString();
        sb.Clear();

        sb.Append("{");
        sb.Append(@"""sEcho"": ");
        sb.AppendFormat(@"""{0}""", sEcho);
        sb.Append(",");
        sb.Append(@"""iTotalRecords"": ");
        sb.Append(totalRecords);
        sb.Append(",");
        sb.Append(@"""iTotalDisplayRecords"": ");
        sb.Append(totalDisplayRecords);
        sb.Append(", ");
        sb.Append(@"""aaData"": [ ");
        sb.Append(outputJson);
        sb.Append("]}");
        outputJson = sb.ToString();

        return outputJson;
    }

    public static int ToInt(string toParse)
    {
        int result;
        if (int.TryParse(toParse, out result)) return result;           

        return result;
    }

}

Now I see when I start to enter into one of the colFilter text boxes in FireBug, that the value are being stored in HttpContext.Current.Request.Params["sSearch_1"] but I'm not sure how I can apply this to the individual column and not a global search. 现在,当我开始输入FireBug中的colFilter文本框之一时,该值将存储在HttpContext.Current.Request.Params["sSearch_1"]但是我不确定如何将其应用于单个列而不是全局搜索。 I will also need to at a later point add the date-range to filter on the MsgDate col. 我还需要稍后添加日期范围以在MsgDate col上进行过滤。

Any help would be appreciated. 任何帮助,将不胜感激。

columnFilter doesn't work very well. columnFilter效果不佳。 there is some bug... 有一些错误...

i recommand another approach and it work well and more flexible. 我建议使用另一种方法,它运作良好且更加灵活。

you can create your own input like (example): 您可以创建自己的输入,例如(示例):

<input id="mysearchfiltercolumn1" type="text" />

in your datatable you can add this : 您可以在数据表中添加以下内容:

var table = $("#tbl").dataTable({
                    //[...]
                    "fnServerParams": function (aoData) {
                        aoData.push({ "name": "mycolumn1", "value": $('#mysearchfiltercolumn1').val() });
                        aoData.push({ "name": "mycolumn2", "value": $('#mysearchfiltercolumn2').val() });
                        aoData.push({ "name": "mycolumn3", "value": $('#mysearchfiltercolumn2').val() });
                    }
             });

...and you bind your inputs like this : ...然后您像这样绑定输入:

$("#mysearchfiltercolumn1,#mysearchfiltercolumn2,#mysearchfiltercolumn3").bind('keyup',function (event) {
                        table.fnDraw();   
                });

and server-side you should see Request['mycolumn1'] and do make you want in order to give the result. 在服务器端,您应该看到Request['mycolumn1']并根据需要进行设置。

you can convert HttpContext.Current.Request.Params["sEcho"] by Request['sEcho'] etc... 您可以通过Request['sEcho']等将HttpContext.Current.Request.Params["sEcho"]转换为...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何使用 C#、ASP.NET、SQL Server 端处理实现 jQuery DataTables 插件? - How can I implement jQuery DataTables plugin using C#, ASP.NET, SQL Server side processing? 如何将jQuery DataTables与服务器端处理C#和WebMethod一起使用? - How to use jQuery DataTables with Server-Side Processing C# and WebMethod? datatables.net C# Razor 核心中的服务器端处理,DataTables 警告:表 id= 行列 datatables.net/tn/4 的请求的未知参数 - datatables.net Server-side processing in C# Razor Core, DataTables warning: table id= Requested unknown parameter for row column datatables.net/tn/4 数据表服务器端处理C#MVC - Datatable server side processing c# mvc JQuery Datatables服务器端处理错误 - JQuery Datatables Server Side Processing Bug JQuery Datatables服务器端处理和过滤器 - JQuery Datatables Server Side Processing and Filter Web Api服务器端处理和数据表参数 - Web Api Server Side Processing and DataTables parameters 使用C#在服务器上处理Ajax发布 - processing ajax post on the server using c# 自定义服务器端DataTables处理:“ typeof(Enumerable).GetMethod”为null - Custom server-side DataTables processing: “typeof(Enumerable).GetMethod” is null 服务器端分页似乎不起作用c#asp.net jquery datatables - server side pagination doesn't seem to be working c# asp.net jquery datatables
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM