I am working on a ASP.Net Core MVC C# app (Visual Studio 2022) and it uses jQuery datatable. I am using ajax call to load data from database. On each column header in the datatable, there is a filter icon clicking on which will drop down a filter menu which contains the column data with check box as shown below.
[![enter image description here][1]][1]
The problem is when selecting 1 or more checked box in the filter menu and click OK, the datatable should filter the data in it. But the filter search is not working in my code. Here is the code that I am using in my ASP.Net Core MVC app.
In the Index.cshtml:
@model AMD_WEB.Models.DoorDetails
@{
ViewData["Title"] = "Index";
}
<!DOCTYPE html>
<html lang="en">
<head>
<link href="https://cdn.datatables.net/1.10.12/css/jquery.dataTables.min.css"
type="text/css" rel="stylesheet" media="screen,projection" />
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.97.7/css/materialize.min.css" />
<script src="~/js/jquery-2.2.4.min.js"></script>
<script src="~/js/jquery.datatables.min.js"></script>
<script src="~/js/materialize.min.js"></script>
<style>
table.dataTable th {
border-bottom: 1px solid #333;
border-right: 1px solid #333;
}
table.dataTable td {
border-bottom: 1px solid #333;
border-right: 1px solid #333;
}
.filterIcon {
height: 16px;
width: 16px;
}
.modalFilter {
display: none;
height: auto;
background: #FFF;
border: solid 1px #ccc;
padding: 8px;
position: absolute;
z-index: 1001;
}
.modalFilter .modal-content {
max-height: 250px;
overflow-y: auto;
}
.modalFilter .modal-footer {
background: #FFF;
height: 35px;
padding-top: 6px;
}
.modalFilter .btn {
padding: 0 1em;
height: 28px;
line-height: 28px;
text-transform: none;
}
#mask {
display: none;
background: transparent;
position: fixed;
left: 0;
top: 0;
z-index: 1;
width: 100%;
height: 100%;
opacity: 1000;
}
</style>
<script>
$(document).ready(function () {
$("#example").DataTable({
serverSide: true,
sortable: true,
filter: true,
searchDelay: 1000,
lengthMenu: [[5, 10, 50, -1], [5, 10, 50, "All"]],
language: { searchPlaceholder: "Brand, Buying Group" },
scrollCollapse: true,
ajax: {
url: '/DOOR_MANAGEMENT/LoadDoors',
type: 'GET',
datatype: 'json',
headers: { 'RequestVerificationToken': 'your json token' },
data: (d) => {
return { draw: d.draw, start: d.start, length: d.length, search: d.search.value, FilterByColumn: d.columns[d.order[0].column].data, ASC_DSEC: d.order[0].dir }
},
beforeSend: () => { ShowLoader(); },
complete: () => { HideLoader(); },
dataSrc: (json) => {
json = json.data;
for (var i = 0, ien = json.length; i < ien; i++) {
json[i]['sites'] = '<button style="height:25px;width:60px"> Site </button>';
}
return json;
}
},
columnDefs: [{ className: "dt-center", targets: [1, 2, 3] }],
columns: [
{ data: 'door_id', title: 'DOOR ID', autoWidth: false, visible: false },
{ data: 'brand', title: 'Brand Code', autoWidth: true, searchable: true },
{ data: 'buying_group', title: 'Buying Group', autoWidth: true },
{ data: 'setting_name', title: 'Setting Name', autoWidth: true },
{ data: 'sites', title: 'Site(s)', autoWidth: true, orderable: false },
{ data: 'tracking_weeks', title: 'Tracking Weeks', autoWidth: true }
],
initComplete: function () {
configFilter(this, [0, 1, 2, 4]);
}
});// datatable
$('#example_length,#example_filter').hide();
});
function configFilter($this, colArray) {
setTimeout(function () {
var tableName = $this[0].id;
var columns = $this.api().columns();
$.each(colArray, function (i, arg) {
$('#' + tableName + ' th:eq(' + arg + ')').append('<img src="http://www.icone-png.com/png/39/38556.png" class="filterIcon" onclick="showFilter(event,'' + tableName + '_' + arg + '')" />');
});
var template = '<div class="modalFilter">' +
'<div class="modal-content">' +
'{0}</div>' +
'<div class="modal-footer">' +
'<a href="#!" onclick="clearFilter(this, {1}, '{2}');" class=" btn left waves-effect waves-light">Clear</a>' +
'<a href="#!" onclick="performFilter(this, {1}, '{2}');" class=" btn right waves-effect waves-light">Ok</a>' +
'</div>' +
'</div>';
$.each(colArray, function (index, value) {
columns.every(function (i) {
if (value === i) {
var column = this, content = '<input type="text" class="filterSearchText" onkeyup="filterValues(this)" /> <br/>';
var columnName = $(this.header()).text().replace(/s+/g, "_");
var distinctArray = [];
column.data().each(function (d, j) {
if (distinctArray.indexOf(d) == -1) {
var id = tableName + "_" + columnName + "_" + j;
content += '<div><input type="checkbox" value="' + d + '" id="' + id + '"/><label for="' + id + '"> ' + d + '</label></div>';
distinctArray.push(d);
}
});
var newTemplate = $(template.replace('{0}', content).replace('{1}', value).replace('{1}', value).replace('{2}', tableName).replace('{2}', tableName));
$('body').append(newTemplate);
modalFilterArray[tableName + "_" + value] = newTemplate;
content = '';
}
});
});
}, 50);
}
var modalFilterArray = {};
function showFilter(e, index) {
var table = $('#' + index.split('_')[0]).DataTable();
var columnIdx = parseInt(index.split('_')[1]);
var column = table.column(columnIdx);
var filterContainer = $(modalFilterArray[index]);
var content = '<input type="text" class="filterSearchText" onkeyup="filterValues(this)" /> <br/>';
var distinctArray = [];
var columnMapping = {
0: 'brand',
1: 'buying_group',
2: 'setting_name',
3: 'sites',
4: 'tracking_weeks'
};
var propertyName = columnMapping[columnIdx];
table.rows({ search: 'applied' }).every(function (rowIdx, tableLoop, rowLoop) {
//var data = this.data()[columnIdx];
var data = this.data()[propertyName];
if (distinctArray.indexOf(data) == -1) {
var id = index + "_" + rowIdx;
content += '<div><input type="checkbox" value="' + data + '" id="' + id + '"/><label for="' + id + '"> ' + data + '</label></div>';
distinctArray.push(data);
}
});
filterContainer.find('.modal-content').html(content);
$('.modalFilter').hide();
var th = $(e.target).parent();
var pos = th.offset();
filterContainer.width(th.width() * 0.75);
filterContainer.css({ 'left': pos.left, 'top': pos.top }).show();
$('#mask').show();
e.stopPropagation();
}
function filterValues(node) {
var searchString = $(node).val(); //.toUpperCase().trim();
var rootNode = $(node).parent();
if (searchString == '') {
rootNode.find('div').show();
} else {
rootNode.find("div").hide();
rootNode.find("div:contains('" + searchString + "')").show();
}
}
function performFilter(node, i, tableId) {
var rootNode = $(node).parent().parent();
var searchString = '', counter = 0;
rootNode.find('input:checkbox').each(function (index, checkbox)
{
if (checkbox.checked)
{
searchString += (counter == 0) ? checkbox.value : '|' + checkbox.value;
counter++;
}
});
$('#' + tableId).DataTable().column(i).search(searchString, true, false).draw();
rootNode.hide();
$('#mask').hide();
}
function clearFilter(node, i, tableId) {
var rootNode = $(node).parent().parent();
rootNode.find(".filterSearchText").val('');
rootNode.find('input:checkbox').each(function (index, checkbox) {
checkbox.checked = false;
$(checkbox).parent().show();
});
$('#' + tableId).DataTable().column(i).search('', true, false).draw();
rootNode.hide();
$('#mask').hide();
}
</script>
</head>
<body>
<div id="mask"></div>
<table id="example" class="bordered material-table centered striped green lighten-1">
</table>
</body>
</html>
In the DOOR_MANAGEMENT Controller class, the method for loading data is shown below:
public IActionResult LoadDoors(int draw = 1, int start = 0, int length = 10, string search = "", string FilterByColumn = "", string ASC_DSEC = "")
{
List<DoorDetails> ListData = new List<DoorDetails>();
int recordsTotal = 0;
DateTime aDate = DateTime.Now;
DoorDetails dm = new DoorDetails();
dm.door_id = 1;
dm.brand = "BM";
dm.buying_group = "Silly USA";
dm.setting_name = "Settings1";
dm.datamodel = 13;
dm.tracking_weeks = 1;
DoorDetails dm1 = new DoorDetails();
dm1.door_id = 2;
dm1.brand = "NB";
dm1.buying_group = "John USA";
dm1.setting_name = "Settings2";
dm1.datamodel = 16;
dm1.tracking_weeks = 14;
DoorDetails dm11 = new DoorDetails();
dm11.door_id = 3; ;
dm11.brand = "JA";
dm11.buying_group = "Mathew UK";
dm11.setting_name = "Settings 3";
dm11.datamodel = 17;
dm11.tracking_weeks = 45;
ListData.Add(dm);
ListData.Add(dm1);
ListData.Add(dm11);
recordsTotal = ListData.Count();
var jsonData = new { draw = draw, recordsFiltered = recordsTotal,
recordsTotal = recordsTotal, data = ListData };
return Ok(jsonData);
}
And the DoorDetails Model class is shown below:
namespace AMD_WEB.Models
{
public class DoorDetails
{
public int door_id { get; set; }
public string brand { get; set; }
public string buying_group { get; set; }
public string setting_name { get; set; }
public int? datamodel { get; set; }
public int? tracking_weeks { get; set; }
}
}
The problem is in the below section of code:
function performFilter(node, i, tableId) {
var rootNode = $(node).parent().parent();
var searchString = '', counter = 0;
rootNode.find('input:checkbox').each(function (index, checkbox)
{
if (checkbox.checked)
{
searchString += (counter == 0) ? checkbox.value : '|' + checkbox.value;
counter++;
}
});
$('#' + tableId).DataTable().column(i).search(searchString, true,
false).draw(); // HERE SEARCH IS NOT WORKING
rootNode.hide();
$('#mask').hide();
}
How to correct it ? I want to filter the datatable when clicking OK on the filter menu.
2
Answers
1.
Draw
method doesn’t work,we shouddestory
the table and then initialize table.2.
"searchString"
can not be passed to the method because no field to received.I defind two variables to pass the parameters.I copy your code meet some problems,I don’t know if you have the same problem,so I put comments on all my changes. I hope this can help you.
controller.cs:
.cshtml:
The results are :
checkbox
and column ,then we should editshowFilter
,performFilter
,clearFilter
threefunctions,add the array param to the Action in
resetDataTable
function.I updown all code in in case there’s someting missing:here is the script code:
2.The action process data.
1).create a filterArr model :
2).Action (your project should have use database,so I do not write processing logic,you can see:https://learn.microsoft.com/en-us/sql/t-sql/queries/where-transact-sql?view=sql-server-ver16 ):
The result are: