ASP.NET Core 2.2 - Filtering Entities


Ken Haggerty
Created 08/25/2019 - Updated 08/25/2019 16:08

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 research project I used for the articles about table functions is published to tables.kenhaggerty.com. I created a topic, ASP.NET Core 2.2 - Table Functions Project for discussions. Access to the source code may be purchased 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


Comment Count = 0

Please log in to comment or follow.

Login Register
Follow to get web notifications when new comments are posted to this article.
Logged in users receive web notifications for new articles, topics and assets.
Web Notifications