New to Telerik UI for ASP.NET MVC? Start a free 30-day trial
Using DropDownList as Boolean Filter in Grid
Environment
Product | Progress® Telerik® UI Grid for UI for ASP.NET MVC |
Description
How can I set up a custom filter for a Boolean column in the Grid and have a DropDownList which lists true, false, all?
Solution
- Create a template function to initialize the DropDownList.
Razor
function boolFilterTemplate(input) {
input.kendoDropDownList({
dataSource: {
data: [
{ text: "True", value: true },
{ text: "False", value: false }
]
},
dataTextField: "text",
dataValueField: "value",
valuePrimitive: true,
optionLabel: "All"
});
}
- Use the
filterMenuInit
event of the Grid to replace the default filter label with more appropriate text.
Razor
function onFilterMenuInit(e) {
if (e.field == "Discontinued") {
// replace default text in filter menu
e.container.find(".k-filter-help-text").text("Show items with value:");
}
}
- Use the
filter
event of the Grid to replace the string value in the generated filter expression with its Boolean equivalent.
Razor
function onFilter(e) {
if (e.field === "Discontinued") {
var filter = e.filter;
if (filter && filter.filters && filter.filters.length > 0) {
var filters = filter.filters;
// convert the filter string value to a boolean one
filters[0].value = (filters[0].value === "true");
}
}
}
Example:
Razor
@(Html.Kendo().Grid<BooleanFilterGrid.Models.OrderViewModel>()
.Name("grid")
.Columns(columns =>
{
columns.Bound(p => p.OrderID).Filterable(false);
columns.Bound(p => p.Freight);
columns.Bound(p => p.IsTrue);
})
.Pageable()
.Scrollable()
.Filterable()
.Events(ev=>ev.Filter("onFilter"))
.HtmlAttributes(new { style = "height:440px;" })
.DataSource(dataSource => dataSource
.Ajax()
.PageSize(10)
.Read(read => read.Action("Orders_Read", "Grid"))
)
)