ASP.NET Core 2.2 - Filtering Entities

This article will describe how to filter a list of entities. I will assume you have created a new ASP.NET Core 2.2 Razor Pages project. I won't use Identity or Individual User Accounts.

The FREE ASP.NET Core 6.0 - Demos And Utilities Project includes a Table Functions Demo. I created a topic, ASP.NET Core 6.0 - Demos And Utilities Project for discussions. Access to the source code is free for registered users at Manage > Assets.

I will try to add value to many great articles about filtering by using a dropdown and radio button group to select entities.

Edit Index.cshtml.cs, add the filtering properties and queries:
private readonly FoodDbContext _context;

public IndexModel(FoodDbContext context)
{
    _context = context;
}

public int Count { get; set; }

public class RadioButtonProperties
{
    public string Name { get; set; }
    public string ElementId { get; set; }
    public bool IsSelected { get; set; }
}

public List<RadioButtonProperties> ColdStoreRadioButtons { get; set; }

[Display(Name = "Store Cold")]
public string SelectedColdStoreRadio { get; set; }

[Display(Name = "Food Type")]
public FoodType SelectedFoodType { get; set; }

public IList<SelectListItem> FoodTypes { get; set; } = new List<SelectListItem>();

public IList<Food> Foods { get; set; } = new List<Food>();

public void OnGet(FoodType selectedFoodType = FoodType.All, string selectedColdStoreRadio = "All")
{
            
    SelectedFoodType = selectedFoodType;
            
    FoodTypes = new List<SelectListItem>();
    var options = Enum.GetValues(typeof(FoodType));
    foreach (var type in options)
    {
        FoodTypes.Add(new SelectListItem() { Text = type.ToString(), Value = type.ToString() });
    }

    ColdStoreRadioButtons = new List<RadioButtonProperties>()
    {
        new RadioButtonProperties() { Name = "All", ElementId = "ColdStoreRadioButtonAll" },
        new RadioButtonProperties() { Name = "Yes", ElementId = "ColdStoreRadioButtonYes" },
        new RadioButtonProperties() { Name = "No", ElementId = "ColdStoreRadioButtonNo" }
    };

    SelectedColdStoreRadio = selectedColdStoreRadio;

    var foodQuery = _context.Foods.AsQueryable();

    switch (SelectedFoodType)
    {
        case FoodType.Fruit:
            foodQuery = _context.Foods.Where(f => f.FoodType == FoodType.Fruit).AsQueryable();
            break;
        case FoodType.Vegtable:
            foodQuery = _context.Foods.Where(f => f.FoodType == FoodType.Vegtable).AsQueryable();
            break;
        case FoodType.Other:
            foodQuery = _context.Foods.Where(f => f.FoodType == FoodType.Other).AsQueryable();
            break;
        default:
            break;
    }

    switch (SelectedColdStoreRadio)
    {
        case "Yes":
            foodQuery = foodQuery.Where(f => f.ColdStore == true).AsQueryable();
            break;
        case "No":
            foodQuery = foodQuery.Where(f => f.ColdStore == false).AsQueryable();
            break;
        default:
            break;
    }

    Foods = foodQuery.ToList();

    Count = Foods.Count();

}
Edit Index.cshtml, add the dropdown and radio buttons:
<div class="row pt-1 mb-2">
    <div class="col-12 mb-1">
        <a asp-route-currentPage=""
           asp-route-selectedFoodType=""
           asp-route-selectedColdStoreRadio=""
           class="btn btn-primary">Reset</a>
        <h4 class="d-inline ml-2">
            Count = @Model.Count.ToString()
        </h4>
    </div>
</div>
<div class="row mb-2">
    <div class="col-12 col-md-4 col-lg-4">
        <h5 class="">@Html.DisplayNameFor(model => model.SelectedFoodType)</h5>
        <form class="" id="FoodTypeForm" method="get">
            <input type="hidden" asp-for="SelectedColdStoreRadio" />
            <select class="form-control mb-1" asp-for="SelectedFoodType"
                    asp-items="@Model.FoodTypes"
                    onchange="getFoodType();"></select>
        </form>
    </div>
    <div class="col-12 col-md-5 col-lg-6 mb-2">
        <h5 class="">@Html.DisplayNameFor(model => model.SelectedColdStoreRadio)</h5>
        @for (var i = 0; i < Model.ColdStoreRadioButtons.Count(); i++)
        {
            <div class="custom-control custom-radio custom-control-inline">
                <input type="radio" value="@Model.ColdStoreRadioButtons[i].Name" class="custom-control-input"
                       id="@Model.ColdStoreRadioButtons[i].ElementId" asp-for="SelectedColdStoreRadio" />
                <label class="custom-control-label" for="@Model.ColdStoreRadioButtons[i].ElementId">
                    @Model.ColdStoreRadioButtons[i].Name
                </label>
            </div>
        }
    </div>
</div>

Notice the Enum.GetValues(typeof(FoodType)).

Edit Index.cshtml, add the JavaScript:
function getFoodType() {
    document.querySelector('#FoodTypeForm').submit();
}

// After DOMContentLoaded
var coldStoreRadioButtons = document.querySelectorAll('[name="SelectedColdStoreRadio"]');
var rbl = coldStoreRadioButtons.length;
for (var rb = 0; rb < rbl; rb++) {
    coldStoreRadioButtons[rb].addEventListener('click', function (event) {
        var selectFoodType = document.querySelector('#SelectedFoodType');
        var foodType = selectFoodType.options[selectFoodType.selectedIndex].text;
        var coldStore = document.querySelector('input[name="SelectedColdStoreRadio"]:checked').value;
        location.replace('/index?currentPage=1' +
            '&selectedFoodType=' + foodType +
            '&selectedColdStoreRadio=' + coldStore);
    });
}

Build, run and test.

Filtered Table
Update 12/30/2021

Announced the ASP.NET Core 6.0 - Demos And Utilities Project. Updated articles, asset and topic links.

Ken Haggerty
Created 08/25/19
Updated 12/30/21 16:57 GMT

Log In or Reset Quota to read more.

Article Tags:

EF Core JavaScript
Successfully completed. Thank you for contributing.
Contribute to enjoy content without advertisments.
Something went wrong. Please try again.

Comments(0)

Loading...
Loading...

Not accepting new comments.

Submit your comment. Comments are moderated.

User Image
DisplayedName - Member Since ?