Skip to content

Custom filtering

Alexander Krutov edited this page Dec 1, 2016 · 10 revisions

When to use custom filtering

Sometimes it's needed to pass additional parameters anlong 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 paramter 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;

Difference between CustomFilterPredicate and GlobalSearchPredicate

  1. CustomFilterPredicate will be applied even if global search value is not specified;
  2. CustomFilterPredicate applied even when columns are non-searchable;
  3. 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 => customSearchPredicate(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.

Clone this wiki locally