📅 February 23, 2023

Implementing Search with MudBlazor Autocomplete

Implementing search functionality is a common feature in many software applications. I recently wanted to see how to accomplish this in Blazor using MudBlazor. It turned out to be a simple and straightforward process using the Autocomplete component. Below are the steps I took.

Add the control

The first step is to add the MudAutocomplete control to your Razor component. An example is below:

<MudAutocomplete T="ProductEntity"
                    SearchFunc="Search"
                    ToStringFunc="@(product => product is null ? null : $"{product.Name}")" />

Type Parameter

The first thing to point out is the T="ProductEntity". This is setting the type parameter of this MudAutocomplete to ProductEntity which will in turn dictate what the other required attribute methods need to return.

SearchFunc

The SearchFunc attribute requires a Func<string, Task<IEnumerable<T>>>. In the example above, I'm setting SearchFunc to Search which is declared in the code block below:

private Task<IEnumerable<ProductEntity>> Search(string searchTerm)
{
    if (string.IsNullOrEmpty(searchTerm))
    {
        return Task.FromResult(Enumerable.Empty<ProductEntity>());
    }

    var products = Products?
        .Where(product => product.Name.Contains(searchTerm, StringComparison.InvariantCultureIgnoreCase))
        ?? Enumerable.Empty<ProductEntity>();

    return Task.FromResult(products);
}

The method above needs to return a Task<IEnumerable<ProductEntity>>. The method returns an empty result if there is not a search term. If there is, the code returns products where the search term exists in the product name. These calls are not awaited for this example, so I'm usingTask.FromResult to return.

ToStringFunc

This attribute defines how values are displayed in the drop-down list. If you don't include this when using the generic T MudAutocomplete, the fully qualified name is displayed. In my case, I'm displaying the product name: ToStringFunc="@(product => product is null ? null : $"{product.Name}")"

Demo

demo

#development#dotnet#blazor
An unhandled error has occurred. Reload 🗙