- Custom component in filter menu
- Show 24 hours time format in filter dialog
- Customizing filter menu operators list
- Filter by multiple keywords using filter menu
- Customize the default input component of filter menu dialog
- Hide default filter icons while perform filtering through method
- Filter menu events
- Troubleshoot filter menu operator issue
- See also
Contact Support
Filter menu in ASP.NET MVC Grid component
20 Mar 202523 minutes to read
The filter menu in the ASP.NET MVC Grid component allows you to enable filtering and provides a user-friendly interface for filtering data based on column types and operators.
To enable the filter menu, you need to set the FilterSettings.Type property to Menu. This property determines the type of filter UI that will be rendered. The filter menu UI allows you to apply filters using different operators.
Here is an example that demonstrates the usage of the filter menu in the Syncfusion® ASP.NET MVC Grid:
@Html.EJS().Grid("grid").DataSource((IEnumerable<object>)ViewBag.dataSource).AllowFiltering().Height("350px").Columns(col =>
{
col.Field("OrderID").HeaderText("Order ID").Width("120").TextAlign(Syncfusion.EJ2.Grids.TextAlign.Right).Add();
col.Field("CustomerID").HeaderText("Customer ID").Width("150").Add();
col.Field("OrderDate").HeaderText("Order Date").Width("130").TextAlign(Syncfusion.EJ2.Grids.TextAlign.Right).Format("yMd").Add();
col.Field("Freight").HeaderText("Freight").Width("120").Format("C2").TextAlign(Syncfusion.EJ2.Grids.TextAlign.Right).Add();
col.Field("ShipCountry").HeaderText("Ship Country").Width("120").Add();
}).FilterSettings(filter => { filter.Type(Syncfusion.EJ2.Grids.FilterType.Menu); }).Render()
public IActionResult Index()
{
ViewBag.dataSource = OrderDetails.GetAllRecords();
return View();
}
- AllowFiltering must be set as true to enable filter menu.
- By setting
Columns.AllowFiltering
as false will prevent filter menu rendering for a particular column.
Custom component in filter menu
You can enhance the filtering experience in the Syncfusion® ASP.NET MVC Grid component by customizing the filter menu with custom components. This allows you to replace the default search box with custom components like dropdowns or textboxes. By default, the filter menu provides an autocomplete component for string type columns, a numeric textbox for number type columns, and a dropdown component for boolean type columns, making it easy to search for values.
To customize the filter menu, you can make use of the Column.Filter.Ui
property. This property allows you to integrate your desired custom filter component into a specific column of the Grid. To implement a custom filter UI, you need to define the following functions:
- create: This function is responsible for creating the custom component for the filter.
- write: The write function is used to wire events for the custom component. This allows you to handle changes in the custom filter UI.
- read: The read function is responsible for reading the filter value from the custom component. This is used to retrieve the selected filter value.
For example, you can replace the standard search box in the filter menu with a dropdown component. This enables you to perform filtering operations by selecting values from the dropdown list, rather than manually typing in search queries.
Here is a sample code demonstrating how to render a dropdownlist component for the CustomerID column:
@using Newtonsoft.Json;
@{
var filteruiTemplate = new
{
ui = new
{
create = "createCustomFilter",
write = "writeCustomFilter",
read = "readCustomFilter"
}
};
}
@Html.EJS().Grid("grid").DataSource((IEnumerable<object>)ViewBag.dataSource).AllowFiltering().Height("300px").Columns(col =>
{
col.Field("OrderID").HeaderText("Order ID").Width("120").TextAlign(Syncfusion.EJ2.Grids.TextAlign.Right).Add();
col.Field("CustomerID").HeaderText("Customer ID").Width("150").Filter(filteruiTemplate).Add();
col.Field("ShipCity").HeaderText("Ship City").Width("120").Add();
col.Field("ShipName").HeaderText("Ship Name").Width("120").Add();
}).FilterSettings(filter => { filter.Type(Syncfusion.EJ2.Grids.FilterType.Menu); }).Render()
<script>
let dropInstance;
function createCustomFilter(args) {
var filterInputElement = new ej.base.createElement('input', { className: 'filter-input' });
args.target.appendChild(filterInputElement);
dropInstance = new ej.dropdowns.DropDownList({
dataSource: new ej.data.DataManager(@Html.Raw(JsonConvert.SerializeObject(ViewBag.dataSource))),
fields: { text: 'CustomerID', value: 'CustomerID' },
placeholder: 'Select a value',
popupHeight: '200px'
});
dropInstance.appendTo(filterInputElement);
}
function writeCustomFilter(args) {
dropInstance.value = args.filteredValue;
}
function readCustomFilter(args) {
args.fltrObj.filterByColumn(args.column.field, args.operator, dropInstance.value);
}
</script>
public IActionResult Index()
{
ViewBag.dataSource = OrderDetails.GetAllRecords();
return View();
}
Default filter input for CustomerID column
Custom dropdown filter for CustomerID column
Show 24 hours time format in filter dialog
The Syncfusion® ASP.NET MVC Grid provides a feature to display the time in a 24-hour format in the date or datetime column filter dialog. By default, the filter dialog displays the time in a 12-hour format (AM/PM) for the date or datetime column. However, you can customize the default format by setting the type as dateTime and the format as M/d/y HH:mm. To enable the 24-hour time format in the filter dialog, you need to handle the ActionComplete event with requestType
as filterafteropen
and set the timeFormat
of the DateTimePicker
to HH:mm.
Here is an example that demonstrates how to show 24 hours time format in filter dialog:
@Html.EJS().Grid("grid").DataSource((IEnumerable<object>)ViewBag.dataSource).AllowFiltering().Height("300px").Columns(col =>
{
col.Field("OrderID").HeaderText("Order ID").Width("120").TextAlign(Syncfusion.EJ2.Grids.TextAlign.Right).Add();
col.Field("OrderDate").HeaderText("Order Date").Width("130").TextAlign(Syncfusion.EJ2.Grids.TextAlign.Right).Type("datetime").Format("M/d/y HH:mm").Add();
col.Field("ShippedDate").HeaderText("Shipped Date").Width("130").TextAlign(Syncfusion.EJ2.Grids.TextAlign.Right).Type("datetime").Format("M/d/y HH:mm").Add();
col.Field("ShipCountry").HeaderText("Ship Country").Width("120").Add();
}).FilterSettings(filter => { filter.Type(Syncfusion.EJ2.Grids.FilterType.Menu); }).ActionComplete("actionComplete").Render()
<script>
function actionComplete(args) {
if (args.requestType === 'filterAfterOpen') {
var grid = document.getElementById("grid").ej2_instances[0];
let columnObject = grid.getColumnByField(args.columnName);
if (columnObject.type === 'datetime') {
let dateObject = document.getElementById('dateui-' + columnObject.uid)['ej2_instances'][0];
dateObject.timeFormat = 'HH:mm';
}
}
}
</script>
public IActionResult Index()
{
ViewBag.dataSource = OrderDetails.GetAllRecords();
return View();
}
Customizing filter menu operators list
The Syncfusion® ASP.NET MVC Grid enables you to customize the default filter operator list by utilizing the FilterSettings.Operators property. This feature allows you to define your own set of operators that will be available in the filter menu. You can customize operators for string, number, date, and boolean data types.
The available options for customization are:
- stringOperator- defines customized string operator list.
- numberOperator - defines customized number operator list.
- dateOperator - defines customized date operator list.
- booleanOperator - defines customized boolean operator list.
Here is an example of how to customize the filter operators list in Syncfusion® ASP.NET MVC Grid:
@{
var stringOperator = new[] {
new { value = "startsWith", text = "Starts With" },
new { value = "endsWith", text = "Ends With" },
new { value = "contains", text = "Contains" },
new { value = "equal", text = "Equal" },
new { value = "notEqual", text = "Not Equal" }
};
var numberOperator = new[] {
new { value = "equal", text = "Equal" },
new { value = "notEqual", text = "Not Equal" },
new { value = "greaterThan", text = "Greater Than" },
new { value = "lessThan", text = "Less Than" }
};
var dateOperator = new[] {
new { value = "equal", text = "Equal" },
new { value = "notEqual", text = "Not Equal" },
new { value = "greaterThan", text = "After" },
new { value = "lessThan", text = "Before" }
};
var booleanOperator = new[] {
new { value = "equal", text = "Equal" },
new { value = "notEqual", text = "Not Equal" }
};
}
@Html.EJS().Grid("grid").DataSource((IEnumerable<object>)ViewBag.dataSource).AllowFiltering().Height("350px").Columns(col =>
{
col.Field("OrderID").HeaderText("Order ID").Width("120").TextAlign(Syncfusion.EJ2.Grids.TextAlign.Right).Add();
col.Field("CustomerID").HeaderText("Customer ID").Width("130").Add();
col.Field("OrderDate").HeaderText("Order Date").Width("140").TextAlign(Syncfusion.EJ2.Grids.TextAlign.Right).Format("yMd").Add();
col.Field("Verified").HeaderText("Verified").Width("120").DisplayAsCheckBox(true).TextAlign(Syncfusion.EJ2.Grids.TextAlign.Center).Add();
col.Field("ShipName").HeaderText("ShipName").Width("120").Add();
}).FilterSettings(filter => { filter.Type(Syncfusion.EJ2.Grids.FilterType.Menu).Operators(new { stringOperator = stringOperator, numberOperator = numberOperator, dateOperator = dateOperator, booleanOperator = booleanOperator }); }).Render()
public IActionResult Index()
{
ViewBag.dataSource = OrderDetails.GetAllRecords();
return View();
}
Filter by multiple keywords using filter menu
The Syncfusion® ASP.NET MVC Grid allows you to perform filtering actions based on multiple keywords, rather than a single keyword, using the filter menu dialog. To enable this feature, you can set FilterSettings.Type as Menu and render the MultiSelect
component as a custom component in the filter menu dialog.
Here is an example that demonstrates how to perform filtering by multiple keywords using the filter menu in the Syncfusion® ASP.NET MVC Grid:
@using Newtonsoft.Json;
@{
var filteruiTemplate = new
{
ui = new
{
create = "createCustomFilter",
write = "writeCustomFilter",
read = "readCustomFilter"
}
};
}
@Html.EJS().Grid("grid").DataSource((IEnumerable<object>)ViewBag.dataSource).AllowFiltering().Height("430px").Columns(col =>
{
col.Field("OrderID").HeaderText("Order ID").Width("120").TextAlign(Syncfusion.EJ2.Grids.TextAlign.Right).Filter(filteruiTemplate).Add();
col.Field("CustomerID").HeaderText("CustomerID").Width("150").Filter(filteruiTemplate).Add();
col.Field("ShipCity").HeaderText("Ship City").Width("120").Filter(filteruiTemplate).Add();
col.Field("ShipName").HeaderText("Ship Name").Width("120").Filter(filteruiTemplate).Add();
}).FilterSettings(filter => { filter.Type(Syncfusion.EJ2.Grids.FilterType.Menu); }).AllowPaging().Render()
<script>
let dropInstance;
function createCustomFilter(args) {
var filterInputElement = ej.base.createElement('input', {
className: 'filter-input',
});
args.target.appendChild(filterInputElement);
var fieldName = args.column.field;
var dropDownData = ej.data.DataUtil.distinct(@Html.Raw(JsonConvert.SerializeObject(ViewBag.dataSource)), fieldName);
dropInstance = new ej.dropdowns.MultiSelect({
dataSource: dropDownData,
placeholder: 'Select a value',
popupHeight: '200px',
allowFiltering: true,
mode: 'Delimiter',
});
dropInstance.appendTo(filterInputElement);
}
function writeCustomFilter(args) {
var fieldName = args.column.field;
var filteredValue = [];
var grid = document.getElementById("grid").ej2_instances[0];
grid.filterSettings.columns.forEach((item) => {
if (item.field === fieldName && item.value) {
filteredValue.push(item.value);
}
});
if (filteredValue.length > 0) {
dropInstance.value = filteredValue;
}
}
function readCustomFilter(args) {
var grid = document.getElementById("grid").ej2_instances[0];
grid.removeFilteredColsByField(args.column.field);
args.fltrObj.filterByColumn(
args.column.field,
args.operator,
dropInstance.value
);
}
</script>
public IActionResult Index()
{
ViewBag.dataSource = OrderDetails.GetAllRecords();
return View();
}
Customize the default input component of filter menu dialog
You have the flexibility to customize the default settings of input components within the menu filter by utilizing the Params
property within the column definition of Filter
. This allows you to modify the behavior of specific filter components to better suit your needs.
Column Type | Default component | Customization | API Reference |
---|---|---|---|
String | AutoComplete | Eg: { params: { autofill: false }} | AutoComplete API |
Number | NumericTextBox | Eg: { params: { showSpinButton: false }} | NumericTextBox API |
Boolean | DropDownList | Eg: { params: { sortOrder:’Ascending’}} | DropDownList API |
Date | DatePicker | Eg: { params: { weekNumber: true }} | DatePicker API |
DateTime | DateTimePicker | Eg: { params: { showClearButton: true }} | DateTimePicker API |
To know more about the feature, refer to the Getting Started documentation and API Reference
In the example provided below, the OrderID and Freight columns are numeric columns. When you open the filter dialog for these columns, you will notice that a NumericTextBox
with a spin button is displayed to change or set the filter value. However, using the Params
property, you can hide the spin button specifically for the OrderID column.
@Html.EJS().Grid("grid").DataSource((IEnumerable<object>)ViewBag.dataSource).AllowFiltering().Columns(col =>
{
col.Field("OrderID").HeaderText("Order ID").Width("120").TextAlign(Syncfusion.EJ2.Grids.TextAlign.Right).
Filter(new { @params = new Syncfusion.EJ2.Inputs.NumericTextBox() { ShowSpinButton= false} }).Add();
col.Field("CustomerID").HeaderText("CustomerID").Width("150").Add();
col.Field("ShipCity").HeaderText("Ship City").Width("120").Add();
col.Field("ShipName").HeaderText("Ship Name").Width("120").Add();
}).FilterSettings(filter => { filter.Type(Syncfusion.EJ2.Grids.FilterType.Menu); }).AllowPaging().Render()
public IActionResult Index()
{
ViewBag.dataSource = OrderDetails.GetAllRecords();
return View();
}
Hide default filter icons while perform filtering through method
When performing filtering programmatically using methods in the Syncfusion® ASP.NET MVC Grid component, you may want to hide the default filter icons to provide a simpler interface.
To customize the filter icon in the Grid, use the display property of the filtermenu as mentioned below
.e-filtermenudiv.e-icons.e-icon-filter {
display: none;
}
The following example demonstrate how to hide the default filter icons while filtering the CustomerID column programmatically using a method.
<div style="padding-bottom:20px">
@Html.EJS().Button("performFilter").CssClass("e-primary filter-button").Content("Filter Customer ID Column").Render()
@Html.EJS().Button("clearFilter").CssClass("e-primary").Content("Clear Filter").Render()
</div>
@Html.EJS().Grid("grid").DataSource((IEnumerable<object>)ViewBag.dataSource).Height("350px").AllowFiltering().Columns(col =>
{
col.Field("OrderID").HeaderText("Order ID").Width("120").TextAlign(Syncfusion.EJ2.Grids.TextAlign.Right).Add();
col.Field("CustomerID").HeaderText("CustomerID").Width("150").Add();
col.Field("ShipCity").HeaderText("Ship City").Width("120").Add();
col.Field("ShipName").HeaderText("Ship Name").Width("120").Add();
}).FilterSettings(filter => { filter.Type(Syncfusion.EJ2.Grids.FilterType.Menu); }).AllowPaging().Render()
<script>
document.getElementById('performFilter').onclick = handleClickEvent;
document.getElementById('clearFilter').onclick = handleClickEvent;
function handleClickEvent(event) {
var grid = document.getElementById("grid").ej2_instances[0];
event.target.id==="performFilter" ? grid.filterByColumn('CustomerID', 'startswith', 'V'):grid.clearFiltering();
}
</script>
<style>
.filter-button {
margin-right: 10px;
}
.e-filtermenudiv.e-icons.e-icon-filter {
display: none;
}
</style>
public IActionResult Index()
{
ViewBag.dataSource = OrderDetails.GetAllRecords();
return View();
}
Filter menu events
The Syncfusion® ASP.NET MVC Grid offers the ActionBegin and ActionComplete events, which provide information about the actions being performed. Within the event handlers, you receive an argument named requestType
. This argument specifies the action
that is being executed, such as filterbeforeopen
, filterafteropen
, or filtering
. By analyzing this action type, you can implement custom logic or showcase messages.
filtering - Defines current action as filtering.
filterbeforeopen - Defines current action as filter dialog before open.
filterafteropen - Defines current action as filter dialog after open.
Here’s an example of how to use these events to handle filter menu action in the Syncfusion® ASP.NET MVC Grid:
<div class='event-message' id='actionBeginMessage'></div>
<div class='event-message' id='actionCompleteMessage'></div>
@Html.EJS().Grid("grid").DataSource((IEnumerable<object>)ViewBag.dataSource).Height("350px").AllowFiltering().Columns(col =>
{
col.Field("OrderID").HeaderText("Order ID").Width("120").TextAlign(Syncfusion.EJ2.Grids.TextAlign.Right).Add();
col.Field("CustomerID").HeaderText("CustomerID").Width("150").Add();
col.Field("ShipCity").HeaderText("Ship City").Width("120").Add();
col.Field("ShipName").HeaderText("Ship Name").Width("120").Add();
}).FilterSettings(filter => { filter.Type(Syncfusion.EJ2.Grids.FilterType.Menu); }).ActionBegin("actionBegin").ActionComplete("actionComplete").AllowPaging().Render()
<script>
function actionBegin(args) {
var message=document.getElementById('actionBeginMessage');
if (args.requestType == 'filterBeforeOpen' && args.columnType === "number") {
args.filterModel.customFilterOperators.numberOperator = [
{ value: "equal", text: "Equal" },
{ value: "notequal", text: "Not Equal" }];
message.innerText ='Filter operators for number column were customized using the filterBeforeOpen action in the actionBegin event';
}
else{
message.innerText= args.requestType + ' action is triggered in actionBegin event'
}
if(args.requestType == 'filtering' && args.currentFilteringColumn == 'ShipCity'){
args.cancel=true;
message.innerText= args.requestType + ' is not allowed for ShipCity column';
}
}
function actionComplete(args) {
var message=document.getElementById('actionCompleteMessage');
if(args.requestType === 'filterAfterOpen') {
message.innerText ='Applied CSS for filter dialog during filterAfterOpen action';
args.filterModel.dlgDiv.querySelector('.e-dlg-content').style.background = '#eeeaea';
args.filterModel.dlgDiv.querySelector('.e-footer-content').style.background = '#30b0ce';
}
if(args.requestType == 'filtering'){
message.innerText = args.requestType + ' action is triggered in actionComplete event';
}
}
</script>
<style>
.event-message {
padding: 10px;
color: red;
text-align: center;
}
</style>
public IActionResult Index()
{
ViewBag.dataSource = OrderDetails.GetAllRecords();
return View();
}
Troubleshoot filter menu operator issue
When using the filter menu, the UI displays operators for all columns based on the data type of the first data it encounters. If the first data is empty or null, it may not work correctly. To overcome this issue, follow these steps to troubleshoot and resolve it:
Explicitly Define Data Type: When defining columns in your ASP.NET MVC Grid component, make sure to explicitly specify the data type for each column. You can do this using the type property within the columns configuration. For example:
@Html.EJS().Grid("Grid").DataSource((IEnumerable<object>)ViewBag.dataSource).AllowFiltering().Columns(col =>
{
col.Field("OrderID").HeaderText("Order ID").Type("number").Width("120").Add();
col.Field("CustomerID").HeaderText("CustomerID").Type("string").Width("150").Add();
<!-- Define data types for other columns as needed -->
}).FilterSettings(filter => { filter.Type(Syncfusion.EJ2.Grids.FilterType.Menu); }).Render()
Handle Null or Empty Data: If your data source contains null or empty values, make sure that these values are appropriately handled within your data source or by preprocessing your data to ensure consistency.
Check Data Types in Data Source: Ensure that the data types specified in the column definitions match the actual data types in your data source. Mismatched data types can lead to unexpected behavior.