【问题标题】:C# ASP.net MVC Ajax MySQL DATATABLES Column searching can't pass search value to ControllerC# ASP.net MVC Ajax MySQL DATATABLES 列搜索无法将搜索值传递给控制器
【发布时间】:2019-09-20 19:12:05
【问题描述】:

努力实现

使用 Datatable,我正在尝试实现列搜索。我希望将search[value] 和column index 传递给Controller,我有一个filter method,它将过滤和加载列表。

我的尝试

使用以下代码,我将keyup change 绑定到每一列。在keyup change 期间,我设法从表中得到valueData 和column index

    table.columns().eq(0).each(function (colIdx) {

        $('input', $('.filters td')[colIdx]).bind('keyup change', function () {
            var searchColIndex = $(this).parent().index();
            //=== During keyup or change, it will go through each column
            var columnIndex = colIdx;

            //=== When the searchCol matches the columnIndex
            if (searchColIndex == columnIndex) {
                //=== Ideally will call Draw and pass the value to Controller
                var valuedata = $(this).val();
                //table.column(0).search($(this).val()).draw();
                table
                 .column(colIdx)
                 .search(valuedata)
                 .draw();
            }

        });
    });

Controllers 无法获取search value 或column index

但如果我在右上角搜索框搜索,Controllers 可以请求值

代码 https://github.com/BROMVC5/BROSTANDARD.git

穆拉特建议

    var table = $('#tablePassword').DataTable({

        "paging": true,
        "ordering": true,
        "processing": true, // control the processing indicator.
        "serverSide": true, // recommended to use serverSide when data is more than 10000 rows for performance reasons
        "info": true,   // control table information display field
        "lengthChange": true,
        "lengthMenu": [[5, 20, 50, -1], [5, 20, 50, "All"]],    // use the first inner array as the page length values and the second inner array as the displayed options
        "colReorder": true,
        "orderMulti": true, // for disable multiple column at once

        "language": {
            searchPlaceholder: "Search records"
        },

        "order": [["3", "desc"]], //=== Not working during stateSave

        //"ajax":{
        //    "url": "/Password/AjaxGetJsonData",
        //    "type": "POST"
        //},
        "AjaxSource": "/Password/AjaxGetJsonData",
        "fnServerData": function (sSource, aoData, fnCallback) {
            aoData.push({ "name": "all", "value": true });
            $.getJSON(sSource, aoData, function (json) {
                fnCallback(json)
            });
        },

        //*** Added the following code ****
        "columnDefs": [
            {
                "width": "5%", "targets": 'NumCol', "data": "id",
                "orderable": false,
                "render": function (data, type, row, meta) {
                    return meta.row + meta.settings._iDisplayStart + 1;
                }
            },
            {
                "targets": 'LoginCol', 
                "data": "LoginID", "orderable": true
            },
            {
                "targets": 'NameCol', 
                "data": "Name", "orderable": true
            },
            {
                "targets": 'DtCreatedCol', 
                "data": "DateCreated", "orderable": true
            },
            {
                "targets": 'EditCol', // The third column
                "className": "text-center",
                "orderable": false,
                "render": function (data, type, full, meta) {
                    return '<a href="/Password/PasswordDet/' + full.AutoINC + '"><img src="../../Content/myPics/edit-2-24.png" ></a>';
                }
            }
        ],

   });


   $('body').on('click', '#btnGet', function () {

        //to get currently clicked row object
        var row = $(this).parents('tr')[0];

        //to get currently clicked row data
        var rowData = table.row(row).data();

        //to get currently clicked row id (first column value (at index [0])
        var rowId = rowData[0];

        var row = $(this).closest("tr"),            // Finds the closest row <tr>
        rowId = row.find("td:nth-child(1)").text();
    });

Murat 建议的控制器未调用并挂起

【问题讨论】:

  • 您是否在Request.QueryString 中获得任何数据?你在AjaxGetJsonData Get 或Post 上使用什么HttpVerb?
  • 只需使用 Request["search[value]"]。我认为这会奏效。
  • @UxmaanAli 无法使用 Request["search[value]"]。
  • @vikscool 我正在使用Get 我已经发布了 Ajax 代码和其他内容。
  • 您获得search[value] 的blank/empty 字符串的原因是您启用了"filter": true,它启用了表格右上角的搜索框。您正在尝试从每列的各个搜索框中调用搜索,但您正在读取的值来自主搜索框。因此,将读取逻辑更改为:columns[index][search][value] 以使搜索工作。

标签: c# ajax asp.net-mvc datatable datatables


【解决方案1】:

试试这个:

var table;
$(document).ready(function () {
    table = $('#tablePassword).DataTable();
});

$('body').on('click', '#btnGet', function () {

    //to get currently clicked row object
    var row = $(this).parents('tr')[0];

    //to get currently clicked row data
    var rowData = table.row(row).data();

    //to get currently clicked row id (first column value (at index [0])
    var rowId = rowData[0];
});

为了在 jQuery DataTables 中发布额外的参数,除了 ajaxSource 之外,请使用 fnServerData 方法,如下所示(不要忘记在 Controller 方法中使用相同的参数名称):

// code omitted for brevity

"serverSide": true,
"ajaxSource": "/Password/AjaxGetJsonData", 

//fnServerData used to inject the parameters into the AJAX call sent to the server-side
"fnServerData": function (sSource, aoData, fnCallback) {
    aoData.push({ "name": "all", "value": true });
    $.getJSON(sSource, aoData, function (json) {
        fnCallback(json)
    });
},

更新: 请不要忘记在 Controller 方法上使用相同的参数名称。您还可以使用以下方法从 DataTable 中获取行值:

var row = $(this).closest("tr"),            // Finds the closest row <tr>
rowId = row.find("td:nth-child(1)").text(); // Finds the 1st <td> element (Id)

这是此解决方案的控制器和模型部分:

控制器:

/// <summary>
/// Returns data by the criterion
/// </summary>
/// <param name="param">Request sent by DataTables plugin</param>
/// <returns>JSON text used to display data
/// <list type="">
/// <item>sEcho - same value as in the input parameter</item>
/// <item>iTotalRecords - Total number of unfiltered data. This value is used in the message: 
/// "Showing *start* to *end* of *iTotalDisplayRecords* entries (filtered from *iTotalDisplayRecords* total entries)
/// </item>
/// <item>iTotalDisplayRecords - Total number of filtered data. This value is used in the message: 
/// "Showing *start* to *end* of *iTotalDisplayRecords* entries (filtered from *iTotalDisplayRecords* total entries)
/// </item>
/// <item>aoData - Twodimensional array of values that will be displayed in table. 
/// Number of columns must match the number of columns in table and number of rows is equal to the number of records that should be displayed in the table</item>
/// </list>
/// </returns>
[Authorize(Roles = "CanViewLab")]
public ActionResult GetLabs(JQueryDataTableParamModel param, bool isAll)
{          
    var allRecords = repository.Labs; //All records
    if (!isAll)
    {
        allRecords = allRecords.Where(m => m.StatusId == Status.Active); //Only active records
    };
    IEnumerable<Lab> filteredRecords;

    //Check whether the users should be filtered by keyword
    if (!string.IsNullOrEmpty(param.sSearch))
    {
        //Used if particulare columns are filtered 
        var nameFilter = Convert.ToString(Request["sSearch_1"]);
        var placeFilter = Convert.ToString(Request["sSearch_2"]);

        //Optionally check whether the columns are searchable at all 
        var isNameSearchable = Convert.ToBoolean(Request["bSearchable_1"]);
        var isPlaceSearchable = Convert.ToBoolean(Request["bSearchable_2"]);

        //filteredRecords = repository.Labs
        filteredRecords = allRecords //For including "isAll" parameter to the "filteredRecords" as "allRecords" parameter
                .Where(c => isNameSearchable && c.Name.ToLower().Contains(param.sSearch.ToLower())
                            ||
                            isPlaceSearchable && c.Place.ToLower().Contains(param.sSearch.ToLower()));
    }
    else
    {
        filteredRecords = allRecords;
    }

    //!!! The number of request variables (bSortable_X) is equal to the iColumns variable.
    var isNameSortable = Convert.ToBoolean(Request["bSortable_1"]);
    var isCodeSortable = Convert.ToBoolean(Request["bSortable_2"]);
    var isStatusNameSortable = Convert.ToBoolean(Request["bSortable_3"]);
    var sortColumnIndex = Convert.ToInt32(Request["iSortCol_0"]);

    Func<Lab, string> orderingFunction = (c => sortColumnIndex == 1 && isNameSortable ? c.Name :
                                                    sortColumnIndex == 2 && isCodeSortable ? c.Place :
                                                    sortColumnIndex == 3 && isStatusNameSortable ? c.StatusName :
                                                "");

    var sortDirection = Request["sSortDir_0"]; // asc or desc
    if (sortDirection == "asc")
        filteredRecords = filteredRecords.OrderBy(orderingFunction);
    else
        filteredRecords = filteredRecords.OrderByDescending(orderingFunction);

    var displayedRecords = filteredRecords.Skip(param.iDisplayStart).Take(param.iDisplayLength);
    var result = from c in displayedRecords select new[] { Convert.ToString(c.Id), c.Name, c.Place, c.StatusName };
    return Json(new
    {
        sEcho = param.sEcho,
        iTotalRecords = allRecords.Count(),
        iTotalDisplayRecords = filteredRecords.Count(),
        aaData = result
    },
    JsonRequestBehavior.AllowGet);
}


型号:

/// <summary>
/// Class that encapsulates most common parameters sent by DataTables plugin
/// </summary>
public class JQueryDataTableParamModel
{
    /// <summary>
    /// Request sequence number sent by DataTable, same value must be returned in response
    /// </summary>       
    public string sEcho{ get; set; }

    /// <summary>
    /// Text used for filtering
    /// </summary>
    public string sSearch{ get; set; }

    /// <summary>
    /// Number of records that should be shown in table
    /// </summary>
    public int iDisplayLength{ get; set; }

    /// <summary>
    /// First record that should be shown(used for paging)
    /// </summary>
    public int iDisplayStart{ get; set; }

    /// <summary>
    /// Number of columns in table
    /// </summary>
    public int iColumns{ get; set; }

    /// <summary>
    /// Number of columns that are used in sorting
    /// </summary>
    public int iSortingCols{ get; set; }

    /// <summary>
    /// Comma separated list of column names
    /// </summary>
    public string sColumns{ get; set; }
}

这是我检索和列出数据的方式:

查看:

<div class="portlet-body form">
    <div class="form-body">
        <table id="dtbLab" class="table table-striped table-bordered table-hover table-checkable order-column">
            <thead>
                <tr>
                    <th> Id </th>
                    <th> Name </th>                             
                    <th> Place </th>
                    <th> Status </th>
                    <!-- (!!! "columnDefs" width SHOULD BE set up in <th> section of column header) -->
                </tr>
            </thead>
            <tbody></tbody>
        </table>
    </div>
</div>

<script>
var table;
$(document).ready(function () {
    table = $('#dtbLab')
        .DataTable({                
            tableTools: {
            "sRowSelect": "single",
            "aButtons": []
            },
            buttons: [],
        "autoWidth": false,
        "serverSide": true,
        "ajaxSource": "/Lab/GetLabs",
        "fnServerData": function (sSource, aoData, fnCallback) {
            aoData.push({ "name": "isAll", "value": isAllChecked }); // Add some extra data to the sender
            $.getJSON(sSource, aoData, function (json) {
                /* Do whatever additional processing you want on the callback, then tell DataTables */
                fnCallback(json);
            });
        },
        "processing": false, //Enable or disable the display of a 'processing' indicator when the table is being processed (e.g. a sort)
        "columns": [
                        {
                            "name": "Id",
                            "width": '5%', /* '5px' */
                            "searchable": false,
                            "sortable": false,
                            "fnRender": function (oObj) {
                                return '<a href=\"Controller/Action/' + oObj.aData[0] + '\">View</a>';
                            }
                        },
                        { "name": "Name", "width": '45%' },
                        { "name": "Code", "width": '45%' },
                        { "name": "Status", "width": '10%' }
        ]       

    });
});
</script>

希望这会有所帮助...

【讨论】:

  • Yildiz,感谢您提出的答案,但我认为这不是我想要的。当我使用fnServerData 时,我似乎无法加载我的list 此外,我如何传递column index 和它们各自的search[value]?如果可以请详细说明
  • 我尝试了您的代码,但您能否详细说明Controllers 使用fnServerData 初始加载页面时,我无法将list 加载到`数据表中
  • Yildiz,如何将数据放入列表项?
  • @HanzCheah 添加了另一个更新。如果对您有帮助,请不要忘记投票并将其标记为 asnwer。
  • 首先,感谢您的帮助,但实际上我还没有找到解决方案。问题是当我听从你的建议时。该页面将不会按上述方式加载。如果你去 GitHub 并按照我的代码。我正在使用CreateData 方法,我将调用MySQL query 并填充到List&lt;DataItem&gt; 对于您的示例,我不确定您如何填充数据库。顺便说一下,改成 POST 的时候,原来的Search at the left hand corner 和Sort by 1 column 就不行了。非常感谢您的帮助。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-02-04
  • 2017-08-10
  • 2017-04-20
  • 1970-01-01
相关资源
最近更新 更多