Using Blazor, rendering elements in a for loop and can’t get @bind to work with a dictionary by index

Let’s define the dictionary I’m using as searchBoardGames[image.Id]

The select is in a foreach loop so I can render multiple select elements because what I’m trying to do is collect data from the user for multiple entries, but using the same list of gameIds. The @foreach loop with the <select> would be something like this:

<div class="image-gallery">
    @foreach (var image in images)
    {
        <div class="image-item">
            <img src="data:image/png;base64,@Convert.ToBase64String(image.ImageData)" alt="Unknown Image" />
            <div id="boardGameSelect" class="board-game-select">
                @if (searchResults.ContainsKey(image.Id) && searchResults[image.Id].Any())
                {
                    <select id="@selectInputId" @bind="searchBoardGames[image.Id]">
                        <option value="">-- Select a Board Game --</option>
                        @foreach (var game in searchResults[image.Id])
                        {
                            <option value="@game.Id">@game.Name</option>
                        }
                    </select>
                }
            </div>
        </div>
    }
</div>

So now the problem is the @bind=searchBoardGames[image.Id] isn’t going to work, but I can’t figure out how to get around this problem. I can’t add an @onchange because that’s used by @bind and I haven’t been able to construct a method that could return something because it needs to be bound to a Property, not the value of some returned variable.

4

You can use @onchange to manually handle the changes for each <select>, since @bind can’t directly bind to a dictionary key. A whole working demo you could follow:

@page "/"
@rendermode InteractiveServer
<form method="post" @onsubmit="HandleValidSubmit" @formname="TestForm">
    <div class="image-gallery">
        @foreach (var image in images)
        {
            <div class="image-item">
                <img src="data:image/png;base64,@Convert.ToBase64String(image.ImageData)" alt="Unknown Image" />
                <div id="boardGameSelect" class="board-game-select">
                    @if (searchResults.ContainsKey(image.Id) && searchResults[image.Id].Any())
                    {
                        <select id="[email protected]" value="@GetSelectedValue(image.Id)" @onchange="(e) => UpdateSelectedGame(image.Id, e.Value)">
                            <option value="">-- Select a Board Game --</option>
                            @foreach (var game in searchResults[image.Id])
                            {
                                <option value="@game.Id">@game.Name</option>
                            }
                        </select>
                    }
                </div>
            </div>
        }
    </div>

    <button type="submit">Submit</button>
</form>

@code {
    // Dictionary to hold the selected board game for each image
    private Dictionary<int, string> searchBoardGames = new Dictionary<int, string>();

    // List of images (you can replace this with your actual model for images)
     List<ImageModel> images = new List<ImageModel>
    {
        new ImageModel { Id = 1, ImageData =new byte[0] }, // Sample image
        new ImageModel { Id = 2, ImageData = new byte[0]}   // Sample image
    };

    // Dictionary that stores search results for board games per image ID
    private Dictionary<int, List<GameModel>> searchResults = new Dictionary<int, List<GameModel>>
    {
        { 1, new List<GameModel> { new GameModel { Id = "g1", Name = "Catan" }, new GameModel { Id = "g2", Name = "Ticket to Ride" } } },
        { 2, new List<GameModel> { new GameModel { Id = "g3", Name = "Pandemic" }, new GameModel { Id = "g4", Name = "Carcassonne" } } }
    };

    // Method to get the selected value for the current image
    private string GetSelectedValue(int imageId)
    {
        if (searchBoardGames.ContainsKey(imageId))
        {
            return searchBoardGames[imageId];
        }
        return "";
    }

    // Method to update the selected board game for an image
    private void UpdateSelectedGame(int imageId, object selectedGameId)
    {
        if (!string.IsNullOrEmpty(selectedGameId?.ToString()))
        {
            searchBoardGames[imageId] = selectedGameId.ToString();
        }
    }
    private void HandleValidSubmit()
    {
        // Process the selected board games
        foreach (var entry in searchBoardGames)
        {
            Console.WriteLine($"Image {entry.Key} has selected game ID: {entry.Value}");
        }
    }
    // Sample models
    public class ImageModel
    {
        public int Id { get; set; }
        public byte[] ImageData { get; set; }
    }

    public class GameModel
    {
        public string Id { get; set; }
        public string Name { get; set; }
    }
}

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật