PSC.Blazor.Components.AutoComplete 8.0.1

dotnet add package PSC.Blazor.Components.AutoComplete --version 8.0.1                
NuGet\Install-Package PSC.Blazor.Components.AutoComplete -Version 8.0.1                
This command is intended to be used within the Package Manager Console in Visual Studio, as it uses the NuGet module's version of Install-Package.
<PackageReference Include="PSC.Blazor.Components.AutoComplete" Version="8.0.1" />                
For projects that support PackageReference, copy this XML node into the project file to reference the package.
paket add PSC.Blazor.Components.AutoComplete --version 8.0.1                
#r "nuget: PSC.Blazor.Components.AutoComplete, 8.0.1"                
#r directive can be used in F# Interactive and Polyglot Notebooks. Copy this into the interactive tool or source code of the script to reference the package.
// Install PSC.Blazor.Components.AutoComplete as a Cake Addin
#addin nuget:?package=PSC.Blazor.Components.AutoComplete&version=8.0.1

// Install PSC.Blazor.Components.AutoComplete as a Cake Tool
#tool nuget:?package=PSC.Blazor.Components.AutoComplete&version=8.0.1                

AutoComplete for Blazor

The Autocomplete for Blazor component offers simple and flexible autocomplete type-ahead functionality for Blazor WebAssembly and Blazor Server. The component is built with NET8.

For more details about this component, please see this post on PureSourceCode.com. If you need support for this component or you have a suggestion or comment, please use my Forum.

autocomplete-blazor-component

Now, I added the support for custom design to have more stylish autocomplete.

autocomplete-stylish-blazor-component

Installing

You can install from NuGet using the following command:

Install-Package PSC.Blazor.Components.AutoComplete

Or via the Visual Studio package manger.

Setup

Blazor Server applications will need to include the following CSS and JS files in their _Host.cshtml .

Blazor Client applications will need to include the following CSS and JS files in their Index.html .

In the head tag add the following CSS.

<link href="_content/PSC.Blazor.Components.AutoComplete/css/autocomplete.css" rel="stylesheet" />

Then add the JS script at the bottom of the page using the following script tag.

<script src="_content/PSC.Blazor.Components.AutoComplete/js/autocomplete.js"></script>

I would also suggest adding the following using statement to your main _Imports.razor to make referencing the component a bit easier.

@using PSC.Blazor.Components.AutoComplete

Usage

The component can be used standalone or as part of a form. When used in a form the control fully integrates with Blazors forms and authentication system.

Below is a list of all the options available on the AutoComplete.

Templates

  • ResultTemplate (Required) - Allows the user to define a template for a result in the results list
  • SelectedTemplate (Required) - Allows the user to define a template for a selected item
  • HelpTemplate - Allows the user to define a template to show when the MinimumLength to perform a search hasn't been reached
  • NotFoundTemplate - Allows the user to define a template when no items are found
  • FooterTemplate - Allows the user to define a template which is displayed at the end of the results list

Parameters

  • MinimumLength (Optional - Default: 1) - Minimum number of characters before starting a search
  • Debounce (Optional - Default: 300) - Time to wait after last keypress before starting a search
  • MaximumSuggestions (Optional - Default: 10) - Controls the amount of suggestions which are shown
  • Disabled (Optional - Default: false) - Marks the control as disabled and stops any interaction
  • EnableDropDown (Optional - Default: false) - Allows the control to behave as a dropdown
  • DisableClear (Optional - Default : false) - Hides the clear button from the AutoComplete. Users can still change the selection by clicking on the current selection and typing however, they can't clear the control entirely.'
  • ShowDropDownOnFocus (Optional - Default: false) - When enabled, will show the suggestions dropdown automatically when the control is in search mode. If the control has a current value then the user would need to press the enter key first to enter search mode.
  • StopPropagation (Optional - Default: false) - Control the StopPropagation behavior of the input of this component. See this Microsoft document
  • PreventDefault (Optional - Default: false) - Control the PreventDefault behavior of the input of this component. See Microsoft document
  • InputMaskCSS (Optional) - Add a custom CSS class to the selected item(s)
  • ResultContainerCSS (Optional) - Add a custom CSS class to container of the result box
  • ResultItemCSS (Optional) - Add a custom CSS class to each item container in the result box

The control also requires a SearchMethod to be provided with the following signature Task<IEnumerable<TItem>>(string searchText). The control will invoke this method passing the text the user has typed into the control. You can then query your data source and return the result as an IEnumerable for the control to render.

If you wish to bind the result of the selection in the control to a different type than the type used in the search this is also possible. For example, if you passed in a list of Person but when a Person was selected you wanted the control to bind to an int value which might be the Id of the selected Person, you can achieve this by providing a ConvertMethod The convert method will be invoked by the control when a selection is made and will be passed the type selected. The method will need to handle the conversion and return the new type.

If you want to allow adding an item based on the search when no items have been found, you can achieve this by providing the AddItemOnEmptyResultMethod as a parameter. This method will make the NotFoundTemplate selectable the same way a item would normally be, and will be invoked when the user selects the NotFoundTemplate. This method passes the SearchText and expects a new item to be returned.

Local Data Example

<EditForm Model="MyFormModel" OnValidSubmit="HandlValidSubmit">
    <Autocomplete SearchMethod="SearchFilms"
                  @bind-Value="MyFormModel.SelectedFilm">
        <SelectedTemplate>
            @context.Title
        </SelectedTemplate>
        <ResultTemplate>
            @context.Title (@context.Year)
        </ResultTemplate>
    </Autocomplete>
    <ValidationMessage For="@(() => MyFormModel.SelectedFilm)" />
</EditForm>

@code {
    [Parameter] protected IEnumerable<Film> Films { get; set; }

    private async Task<IEnumerable<Film>> SearchFilms(string searchText) 
    {
        return await Task.FromResult(Films.Where(
                   x => x.Title.ToLower().Contains(searchText.ToLower())
               ).ToList());
    }
}

In the example above, the component is setup with the minimum requirements. You must provide a method which has the following signature Task<IEnumerable<T> MethodName(string searchText), to the SearchMethod parameter. The control will call this method with the current search text everytime the debounce timer expires (default: 300ms). You must also set a value for the Value parameter. This will be populated with the item selected from the search results. As this version of the control is integrated with Blazors built-in forms and validation, it must be wrapped in a EditForm component.

The component requires two templates to be provided:

  • SelectedTemplate
  • ResultTemplates

The SelectedTemplate is used to display the selected item and the ResultTemplate is used to display each result in the search list.

Remote Data Example

@inject HttpClient httpClient

<Autocomplete SearchMethod="@SearchFilms"
              @bind-Value="@SelectedFilm"
              Debounce="500">
    <SelectedTemplate>
        @context.Title
    </SelectedTemplate>
    <ResultTemplate>
        @context.Title (@context.Year)
    </ResultTemplate>
    <NotFoundTemplate>
        Sorry, there weren't any search results.
    </NotFoundTemplate>
</Autocomplete>

@code {
    [Parameter] protected IEnumerable<Film> Films { get; set; }

    private async Task<IEnumerable<Film>> SearchFilms(string searchText) 
    {
        var response = await httpClient.GetJsonAsync<IEnumerable<Film>>(
                       $"https://allfilms.com/api/films/?title={searchText}");
        return response;
    }
}

Because you provide the search method to the component, making a remote call is really straight-forward. In this example, the Debounce parameter has been upped to 500ms and the NotFoundTemplate has been specified.

Subscribing to changes in selected values

It is common to want to be able to know when a value bound to the AutoComplete changes. To do this you can't use the standard @bind-Value or @bind-Values syntax, you must handle the change event manually. To do this you must specify the following parameters:

  • Value
  • ValueChanged
  • ValueExpression
  • TValue & TItem (these are not always necessary)

The code below shows an example of how these parameters should be used.

<AutoComplete SearchMethod="SearchPeople"
              TValue="Result"
              TItem="Result"
              Value="selectedResult"
              ValueChanged="SelectedResultChanged" 
              ValueExpression="@(() => selectedResult)"
              placeholder="Search by name...">
</AutoComplete>

@code {
    private MovieCredits movieCredits;
    private Result selectedResult;

    private async Task<IEnumerable<Result>> SearchPeople(string searchText)
    {
        var search = await client.SearchPerson(searchText);
        return search.Results;
    }

    private async Task SelectedResultChanged(Result result)
    {
        selectedResult = result;
        movieCredits = await client.GetPersonMovieCredits(result.Id);
    }
}

Using complex types but only binding to a single property

There are times when you will want to use complex types with the AutoComplete but only bind a certain property of that type. For example, you may want to search against a Person but once a person is selected, only bind to it's Id property. In order to do this you will need to implement the following:

<Autocomplete SearchMethod="GetPeopleLocal"
              ConvertMethod="ConvertPerson"
              @bind-Value="SelectedPersonId"
              placeholder="Search by first name...">
    <SelectedTemplate Context="personId">
        @{
            var selectedPerson = LoadSelectedPerson(personId);

            <text>@selectedPerson?.Firstname @selectedPerson?.Lastname</text>
        }
    </SelectedTemplate>
    <ResultTemplate Context="person">
        @person.Firstname @person.Lastname (Id: @person.Id)
    </ResultTemplate>
</Autocomplete>

@code {
    private List<Person> People = new List<Person>();

    protected override void OnInitialized()
    {
        People.AddRange(new List<Person>() {
            new Person() { Id = 1, Firstname = "Martelle", Lastname = "Cullon" },
            new Person() { Id = 2, Firstname = "Zelda", Lastname = "Abrahamsson" },
            new Person() { Id = 3, Firstname = "Benedetta", Lastname = "Posse" }
        });
    }

    private async Task<IEnumerable<Person>> GetPeopleLocal(string searchText)
    {
        return await Task.FromResult(People.Where(
                    x => x.Firstname.ToLower().Contains(searchText.ToLower())
               ).ToList());
    }

    private int? ConvertPerson(Person person) => person?.Id;

    private Person LoadSelectedPerson(int? id) => 
            People.FirstOrDefault(p => p.Id == id);
}

PureSourceCode.com

PureSourceCode.com is my personal blog where I publish posts about technologies and in particular source code and projects in .NET.

In the last few months, I created a lot of components for Blazor WebAssembly and Blazor Server.

My name is Enrico Rossini and you can contact me via:

Blazor Components

Component name Forum NuGet Website Description
AnchorLink Forum NuGet badge An anchor link is a web link that allows users to leapfrog to a specific point on a website page. It saves them the need to scroll and skim read and makes navigation easier. This component is for Blazor WebAssembly and Blazor Server
Autocomplete for Blazor Forum NuGet badge Simple and flexible autocomplete type-ahead functionality for Blazor WebAssembly and Blazor Server
Browser Detect for Blazor Forum NuGet badge Demo Browser detect for Blazor WebAssembly and Blazor Server
ChartJs for Blazor Forum NuGet badge Demo Add beautiful graphs based on ChartJs in your Blazor application
Clippy for Blazor Forum NuGet badge Demo Do you miss Clippy? Here the implementation for Blazor
CodeSnipper for Blazor Forum NuGet badge Add code snippet in your Blazor pages for 196 programming languages with 243 styles
Copy To Clipboard Forum NuGet badge Add a button to copy text in the clipboard
DataTable for Blazor Forum NuGet badge Demo DataTable component for Blazor WebAssembly and Blazor Server
Google Tag Manager Forum NuGet badge Demo Adds Google Tag Manager to the application and manages communication with GTM JavaScript (data layer).
Icons and flags for Blazor Forum NuGet badge Library with a lot of SVG icons and SVG flags to use in your Razor pages
ImageSelect for Blazor Forum NuGet badge This is a Blazor component to display a dropdown list with images based on ms-Dropdown by Marghoob Suleman. This component is built with NET7 for Blazor WebAssembly and Blazor Server
Markdown editor for Blazor Forum NuGet badge Demo This is a Markdown Editor for use in Blazor. It contains a live preview as well as an embeded help guide for users.
Modal dialog for Blazor Forum NuGet badge Simple Modal Dialog for Blazor WebAssembly
Modal windows for Blazor Forum NuGet badge Modal Windows for Blazor WebAssembly
Quill for Blazor Forum NuGet badge Quill Component is a custom reusable control that allows us to easily consume Quill and place multiple instances of it on a single page in our Blazor application
ScrollTabs NuGet badge Tabs with nice scroll (no scrollbar) and responsive
Segment for Blazor Forum NuGet badge This is a Segment component for Blazor Web Assembly and Blazor Server
Tabs for Blazor Forum NuGet badge This is a Tabs component for Blazor Web Assembly and Blazor Server
Timeline for Blazor Forum NuGet badge This is a new responsive timeline for Blazor Web Assembly and Blazor Server
Toast for Blazor Forum NuGet badge Toast notification for Blazor applications
Tours for Blazor Forum NuGet badge Guide your users in your Blazor applications
TreeView for Blazor Forum NuGet badge This component is a native Blazor TreeView component for Blazor WebAssembly and Blazor Server. The component is built with .NET7.
WorldMap for Blazor Forum NuGet badge Demo Show world maps with your data

C# libraries for .NET6

Component name Forum NuGet Description
PSC.Evaluator Forum NuGet badge PSC.Evaluator is a mathematical expressions evaluator library written in C#. Allows to evaluate mathematical, boolean, string and datetime expressions.
PSC.Extensions Forum NuGet badge A lot of functions for .NET5 in a NuGet package that you can download for free. We collected in this package functions for everyday work to help you with claim, strings, enums, date and time, expressions...

More examples and documentation

Blazor

Blazor & NET8

Product Compatible and additional computed target framework versions.
.NET net6.0 is compatible.  net6.0-android was computed.  net6.0-ios was computed.  net6.0-maccatalyst was computed.  net6.0-macos was computed.  net6.0-tvos was computed.  net6.0-windows was computed.  net7.0 was computed.  net7.0-android was computed.  net7.0-ios was computed.  net7.0-maccatalyst was computed.  net7.0-macos was computed.  net7.0-tvos was computed.  net7.0-windows was computed.  net8.0 was computed.  net8.0-android was computed.  net8.0-browser was computed.  net8.0-ios was computed.  net8.0-maccatalyst was computed.  net8.0-macos was computed.  net8.0-tvos was computed.  net8.0-windows was computed. 
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.

NuGet packages

This package is not used by any NuGet packages.

GitHub repositories

This package is not used by any popular GitHub repositories.

Version Downloads Last updated
8.0.1 1,605 4/17/2024
8.0.0 128 4/11/2024
6.0.29 115 4/11/2024
6.0.28 828 12/14/2023
6.0.27 133 12/10/2023
6.0.26 185 11/13/2023
6.0.25 121 11/13/2023
6.0.24 184 10/25/2023
6.0.23 144 10/23/2023
6.0.21 136 10/23/2023
6.0.20 165 10/16/2023
6.0.14 158 9/30/2023
6.0.13 401 2/28/2023
6.0.12 258 2/28/2023
6.0.11 236 2/28/2023
6.0.10 245 2/28/2023
6.0.9 258 2/28/2023
6.0.8 239 2/28/2023
6.0.7 259 2/28/2023
6.0.1 245 2/22/2023
6.0.0 259 2/20/2023