Can I create a MudAutoComplete MultiColumn Search – Virtualized?

Is it possible to create a Virtualized MudAutoComplete MultiColumn search. See screenshot below. I was able to implement this in Telerik and would like to recreate this in MudBlazor. Note, the binding is on a hidden field ID and the combo box is Virtualized. If Virtualization is not possible the Search can begin after 3 characters of entry.

Below is how I implemented it in Telerik. Perhaps that will clarify what I am looking for.

@page "/GenSingle"
@inject SerOHRDatabase serOHRDatabase
@using Telerik.DataSource
@using Telerik.DataSource.Extensions

<div>Generator Name Search:</div>

<TelerikMultiColumnComboBox TItem="ModtblGenerator"
                            OnRead="@ReadItems"
                            TValue="int"
                            ValueField="@nameof(ModtblGenerator.Id)"
                            TextField="@nameof(ModtblGenerator.GenName)"
                            Filterable="true"
                            @bind-Value="@intSelectedGenID"
                            ItemHeight="28"
                            ListHeight="520px"
                            PageSize="25"
                            ScrollMode="@DropDownScrollMode.Virtual"
                            Width= "250px"
                            OnChange="@GetSelectedGeneratorRecord"
>
    <MultiColumnComboBoxColumns>
        <MultiColumnComboBoxColumn Field="@nameof(ModtblGenerator.GenName)"
                                   Title="Gen Name"
                                   HeaderClass="header"
                                   Class="genNameCell"
                                   Width="250px"></MultiColumnComboBoxColumn>
        <MultiColumnComboBoxColumn Field="@nameof(ModtblGenerator.GenNum)"
                                   Title="Gen Num"
                                   HeaderClass="header"
                                   Width="150px"></MultiColumnComboBoxColumn>
        <MultiColumnComboBoxColumn Field="@nameof(ModtblGenerator.Street)"
                                   Title="Street"
                                   HeaderClass="header"
                                   Width="200px"></MultiColumnComboBoxColumn>
        <MultiColumnComboBoxColumn Field="@nameof(ModtblGenerator.City)"
                                   Title="City"
                                   HeaderClass="header"
                                   Width="150px"></MultiColumnComboBoxColumn>
        <MultiColumnComboBoxColumn Field="@nameof(ModtblGenerator.Province)"
                                   Title="Province"
                                   HeaderClass="header"
                                   Width="150px"></MultiColumnComboBoxColumn>
        <MultiColumnComboBoxColumn Field="@nameof(ModtblGenerator.PostalCode)"
                                   Title="Postal Code"
                                   HeaderClass="header"
                                   Width="150px"></MultiColumnComboBoxColumn>
    </MultiColumnComboBoxColumns>
</TelerikMultiColumnComboBox>

<br />
<br />

@if (selectedGenerator != null)
{
    <ComGenerator Generator="@selectedGenerator" />
}

@code {

    List<ModtblGenerator> lstGenerators;
    int intSelectedGenID;
    ModtblGenerator selectedGenerator;
   
    private void GetSelectedGeneratorRecord()
    {
        selectedGenerator = lstGenerators.Find(x => x.Id == intSelectedGenID);
    }

    //**************************************** Combo Events
    protected async Task ReadItems(MultiColumnComboBoxReadEventArgs args)
    {
        await LoadData();
       
        var result = lstGenerators.ToDataSourceResult(args.Request);
        args.Data = result.Data;
        args.Total = result.Total;
    }

    private async Task LoadData()
    {
        if (lstGenerators == null)
        {
            lstGenerators = await serOHRDatabase.GetAllGenerators();
        }
    }
}

<style>
    .header {
        font-weight: bold;
        color: black;
    }

    .genNameCell {
        color: darkblue;
        font-weight: bolder;
    }
</style>

I don’t think the Task.Delay is a good user experience so I spent some time finding a way around it. Here I use a javascript function to detect if there’s a click on page outside of the popover to close it. I’ve also added a clear mechanism. Script shouldn’t really be in the markup, but shown here for brevity.

@inject IJSRuntime jsRuntime

<script>
    window.registerOutsideClickHandler = (dotNetObj, popoverId) => {
        document.addEventListener('click', (event) => {
            const popoverElement = document.getElementById(popoverId);
            if (popoverElement && !popoverElement.contains(event.target)) {
                dotNetObj.invokeMethodAsync('ClosePopover');
            }
        });
    };
</script>

<MudContainer Class="mt-8">
    <MudGrid>
        <MudItem xs="12">
            <div id="popoverWrapper" @onclick="HasFocus">
                <MudTextField @bind-Value="SearchFor" Label="Search" Immediate="true"
                Adornment="Adornment.End" AdornmentIcon="@Icons.Material.Filled.Clear" OnAdornmentClick="@ClearSearch"></MudTextField>
                <MudPopover Open="@IsOpen"
                            AnchorOrigin="@Origin.BottomCenter" TransformOrigin="@Origin.TopCenter"
                            RelativeWidth="true" Fixed="true">
                    <MudTable T="Element" Items="@Data" Hover="true"
                              RowClass="cursor-pointer" OnRowClick="RowClickEvent" Filter="new Func<Element, bool>(FilterElements)">
                        <HeaderContent>
                            <MudTh>Name</MudTh>
                            <MudTh>Num</MudTh>
                            <MudTh>Street</MudTh>
                            <MudTh>City</MudTh>
                            <MudTh>Province</MudTh>
                            <MudTh>PostalCode</MudTh>
                        </HeaderContent>
                        <RowTemplate>
                            <MudTd DataLabel="Name">@context.Name</MudTd>
                            <MudTd DataLabel="Num">@context.Num</MudTd>
                            <MudTd DataLabel="Street">@context.Street</MudTd>
                            <MudTd DataLabel="City">@context.City</MudTd>
                            <MudTd DataLabel="Province">@context.Province</MudTd>
                            <MudTd DataLabel="Postal Code">@context.PostalCode</MudTd>
                        </RowTemplate>
                    </MudTable>
                </MudPopover>
            </div>
        </MudItem>
        <MudItem xs="12">
            <MudField Label="Selected Value" Variant="Variant.Text">
                @((SearchID ?? 0) > 0 ? SearchID : "Nothing Selected")
            </MudField>
        </MudItem>
    </MudGrid>
</MudContainer>

@code {
    private string SearchFor { get; set; } = string.Empty;
    private int? SearchID { get; set; } = null;
    private bool IsOpen { get; set; } = false;

    protected override async Task OnAfterRenderAsync(bool firstRender)
    {
        if (firstRender)
        {
            // Register the click listener to detect clicks outside the popover
            await jsRuntime.InvokeVoidAsync("registerOutsideClickHandler", DotNetObjectReference.Create(this), "popoverWrapper");
        }
    }

    [JSInvokable]
    public void ClosePopover()
    {
        if (IsOpen)
        {
            IsOpen = false;
            StateHasChanged();
        }
    }

    private void HasFocus()
    {
        IsOpen = true;
    }

    private void ClearSearch()
    {
        SearchFor = string.Empty;
        SearchID = null;
        IsOpen = false;
    }

    private void RowClickEvent(TableRowClickEventArgs<Element> Row)
    {
        SearchID = Row.Item.ID;
        SearchFor = Row.Item.Name;
        IsOpen = false;
    }

    private bool FilterElements(Element Row) => FilterFunc(Row, SearchFor);

    private bool FilterFunc(Element Row, string searchString)
    {
        if (string.IsNullOrWhiteSpace(searchString)) return true;
        foreach (var prop in Row.GetType().GetProperties())
        {
            if (prop.GetValue(Row)?.ToString().Contains(searchString, StringComparison.OrdinalIgnoreCase) == true)
                return true;
        }
        return false;
    }

    public class Element
    {
        public int ID { get; set; }
        public string Name { get; set; }
        public string Num { get; set; }
        public string Street { get; set; }
        public string City { get; set; }
        public string Province { get; set; }
        public string PostalCode { get; set; }
    }
    public List<Element> Data { get; set; } = new List<Element> {
        new Element { ID = 1, Name = "John Doe", Num = "1234", Street = "Main St", City = "Springfield", Province = "IL", PostalCode = "62701" },
        new Element { ID = 2, Name = "Jane Smith", Num = "5678", Street = "Maple Ave", City = "Greenfield", Province = "CA", PostalCode = "93927" },
        new Element { ID = 3, Name = "Michael Brown", Num = "9101", Street = "Elm St", City = "Metropolis", Province = "NY", PostalCode = "10001" }
    };
}

2

mouse0270 on the MudBlazor Discord channel provided me with a solution for the logic of the component and then I tweaked it exactly for my needs.

The delay in LostFocus() of 300 ms is very important. Originally, we had it at 100ms and it wasn’t grabbing the correct ID all the time. You may have to possibly increase it to 500 ms etc…

The OnKeyUp() (which I created) could be optimized to take the isolated record from the DataTable instead of doing the FirstOrDefault search but I don’t know how to implement that or if it’s possible. If it is please let me know.

    <MudContainer Class="mt-8">
    <MudGrid>
        @if (forecasts != null)
        {
            <MudItem xs="12">
                <MudText Typo="Typo.h6">
                    Record Count: <strong>@refMudTable?.GetFilteredItemsCount().ToString("N0")</strong>
                </MudText>
            </MudItem>
            <MudItem xs="12">
                <MudText Typo="Typo.h6">
                    Selected ID: <strong>@(intSelectedID ?? 0)</strong>
                </MudText>
            </MudItem>
        }
        <MudItem xs="12">
            <div>
                <MudItem xs="4">
                    <MudTextField @ref="refUserInputField"
                                  @bind-Value="strUserInput" Label="Weather" Variant="Variant.Outlined" Immediate="true" Clearable="true"
                                  @onfocus="HasFocus" @onblur="LostFocus" @onkeyup="OnKeyUp"
                                  HelperText=@($"Record Count: {@refMudTable?.GetFilteredItemsCount().ToString("N0")}")>
                    </MudTextField>
                </MudItem>
                <MudPopover Open="@blnShowPopOverTable"
                            AnchorOrigin="@Origin.BottomCenter"
                            TransformOrigin="@Origin.TopCenter"
                            RelativeWidth="true"
                            Fixed="true">

                    <MudTable @ref="refMudTable"
                              T="WeatherForecast"
                              Items="@forecasts"
                              Hover="true"
                              RowClass="cursor-pointer"
                              OnRowClick="RowClickEvent"
                              Filter="new Func<WeatherForecast, bool>(FilterElements)"
                              FixedHeader="true"
                              Breakpoint="Breakpoint.Sm"
                              Height="400px"
                              Virtualize="true"
                    >
                        <HeaderContent>
                            <MudTh>Summary</MudTh>
                            <MudTh>Date</MudTh>
                            <MudTh>Temperature C</MudTh>
                            <MudTh>Temperature F</MudTh>
                        </HeaderContent>
                        <RowTemplate>
                            <MudTd DataLabel="Summary">@context.Summary</MudTd>
                            <MudTd DataLabel="Date">@context.Date</MudTd>
                            <MudTd DataLabel="Temperature C">@context.TemperatureC</MudTd>
                            <MudTd DataLabel="Temperature F">@context.TemperatureF</MudTd>
                        </RowTemplate>
                    </MudTable>
                </MudPopover>
            </div>
        </MudItem>
    </MudGrid>
</MudContainer>

@code {

    private WeatherForecast[]? forecasts;
    private MudTable<WeatherForecast>? refMudTable;
    private MudTextField<string> refUserInputField;

    // Default Variables
    private string strUserInput { get; set; } = string.Empty; // What we are searching against
    private int? intSelectedID { get; set; } = null; // The element the user has selected
    private bool blnShowPopOverTable { get; set; } = false; // Handles if the Popover is open or not.

    // When the search field gains focus, show the Popover
    private void HasFocus()
    {
        blnShowPopOverTable = true; // Show the Popover
    }

    // When the search field loses focus, hide the Popover
    private async Task LostFocus()
    {
        await Task.Delay(300); // Await 300ms - This is to make it so that the RowClickEvent will trigger if the user clicks on a Row
        blnShowPopOverTable = false; // Hide the Popover
    }

    private void OnKeyUp(KeyboardEventArgs e)
    {
        blnShowPopOverTable = true;
        if (e.Key == "Enter" || e.Key == "Tab")
        {
            //If there is 1 record displayed in the MudTable and the user presses enter execute RowClickEvent
            if (refMudTable?.GetFilteredItemsCount() == 1)
            {
                // The user isolated for 1 record so Find that record in the MudTable
                var singleItem = refMudTable.Items.FirstOrDefault(item => item.Summary.StartsWith
                            (strUserInput, StringComparison.OrdinalIgnoreCase));
                if (singleItem != null)
                {
                    intSelectedID = singleItem.ID; // Set SearchID Rows Item ID
                    strUserInput = singleItem.Summary; // Set the Search Field to show the full Selected Rows Name
                    refUserInputField.BlurAsync(); // Remove focus from the text field
                    blnShowPopOverTable = false; // Hide the Popover
                }
            }
        }
    }

    // Event to handle when the user clicks on a Row
    private void RowClickEvent(TableRowClickEventArgs<WeatherForecast> Row)
    {
        intSelectedID = Row.Item.ID; // Set SearchID Rows Item ID
        strUserInput = Row.Item.Summary; // Set the Search Field to show the full Selected Rows Name
        blnShowPopOverTable = false; // Hide the Popover
    }

    // Search Function for MudTable
    private bool FilterElements(WeatherForecast Row) => FilterFunc(Row, strUserInput);
    
    // Search Function Logic
    private bool FilterFunc(WeatherForecast Row, string strUserInput)
    {
        // If Search String is Empty, Return True
        if (string.IsNullOrWhiteSpace(strUserInput)) return true;
        // If the Summary of the Row starts with the searchString, Return True
        if (Row.Summary.StartsWith(strUserInput, StringComparison.OrdinalIgnoreCase))
            return true;

        // // Loop through each Prop in forecasts.  Use this if you want to search all columns
        // foreach (var prop in Row.GetType().GetProperties())
        // {
        //     // Convert Prop to ToString and then do a case insensitive StartsWith for matching values
        //     if (prop.GetValue(Row)?.ToString().StartsWith(searchString, StringComparison.OrdinalIgnoreCase) == true) return true;
        // }
        // Default to False

        return false;
    }

    private class WeatherForecast
    {
        public int ID { get; set; }
        public DateOnly Date { get; set; }
        public int TemperatureC { get; set; }
        public string? Summary { get; set; }
        public int TemperatureF => 32 + (int)(TemperatureC / 0.5556);
    }

    protected override async Task OnInitializedAsync()
    {
        var startDate = DateOnly.FromDateTime(DateTime.Now);
        var summaries = new[] { "Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching" };
        forecasts = Enumerable.Range(1, 1000).Select(index => new WeatherForecast
            {
                ID = index,
                Date = startDate.AddDays(index),
                TemperatureC = Random.Shared.Next(-20, 55),
                // Summary = summaries[Random.Shared.Next(summaries.Length)] + index.ToString()
                Summary = "HOT" + index.ToString()
            }).ToArray();
    }
}

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