-
Notifications
You must be signed in to change notification settings - Fork 20
Custom filtering
Sometimes it's needed to pass additional parameters along with datatables.net request and filter an IQueryable
with these parameters' values. DataTables.Queryable supports such functionality too.
For example, we need to pass a value of checkbox with meaning 'OnVacation' and filter persons by this flag.
First you need to add extra parameter to the request by manipulating the data
object as described here:
// client-side code (JavaScript)
$('#example').dataTable({
"ajax": {
"url": "/DataTables/Sample",
"data": function ( d ) {
d.onVacation = $('#checkbox-on-vacation').is(":checked");
}
}
});
Then we need to specify custom filter predicate for the DataTables.Queryable request:
// server-side code (C#)
var checkboxValue = bool.Parse(request["onVacation"]);
request.CustomFilterPredicate = p => p.OnVacation == checkboxValue;
-
CustomFilterPredicate
will be applied even if global search value is not specified; -
CustomFilterPredicate
applied even when columns are non-searchable; -
CustomFilterPredicate
does not belong to any column.
The difference can be easily seen on the example how the resulting LINQ query is costructed (pseudocode):
var queryable = ctx.Persons
.Where(p => customFilterPredicate(p)) // CustomFilterPredicate
.Where(p =>
p.Name.StartsWith(globalSearchValue) || // GlobalSearchPredicate
p.Position.StartsWith(globalSearchValue) || // GlobalSearchPredicate
p.Office.StartsWith(globalSearchValue) // GlobalSearchPredicate
);
As you can see the CustomFilterPredicate
applied first and foremost to all columns. GlobalSearchPredicate
constructed with logical OR
and applied to individual columns.