Search code examples
listcheckboxblazorcheckboxlistblazor-editform

Blazor - InputCheckbox: checking boxes based on what's in a database table


I'm trying to prepopulate checkboxes based on numbers included in a database table. For example, the table entries could include:

USER ID ITEM ID
1 4
1 5
1 10
2 4
2 6
2 54

On my page, I would want to fill out the checkboxes based on the user entered. So user 1 would be (without the pretty Blazor UI of course):

Item Name Checkboxes
Dog(4) X
Cat(5) X
Rabbit(6)
Goat(10) X
Llama(54)

When the page opens I would want the items checked to match what's in the database. I'm hoping I can somehow get that to work by getting the list of numbers from the object item ids (4, 5, and 10 in the example).

I know how to handle Blazor check boxes with booleans and event handlers but am not sure how to base it off a list.


Solution

  • Create a model in your Blazor app that represents the items and whether they are checked or not. For example:

    public class ItemModel
    {
        public int ItemId { get; set; }
        public string ItemName { get; set; }
        public bool IsChecked { get; set; }
    }
    

    Initialize Models with Database Data

    List<ItemModel> items = new List<ItemModel>
    {
        new ItemModel { ItemId = 4, ItemName = "Dog" },
        new ItemModel { ItemId = 5, ItemName = "Cat" }
    };
    
    foreach (var item in items)
    {
        if (userSelectedItems.Contains(item.ItemId))
        {
            item.IsChecked = true; // Compare where "X"
        }
    }
    

    Or u can store the "X" in model and compare

    Bind Checkboxes to Models

    @foreach (var item in items)
    {
        <input type="checkbox" @bind="item.IsChecked">@item.ItemName (@item.ItemId)
    }