In this article, we are going to create an autocomplete feature. We will use Typeahead to implement autocomplete.

I’m assuming you already created a blazor server-side application, if not, you can follow these steps to create application.

Let’s start

Open Nuget – Solution from Tools > NuGet Package Manager > Manage NuGet Package For Solution.

Search for “Blazored.Typeahead” and install it.

Open “_Host.cshtml” file and add the following CSS and script links.

Add CSS link inside “<Head>” tag.

<link href="_content/Blazored.Typeahead/blazored-typeahead.css" rel="stylesheet" />

Add script link inside “<body>” tag.

<script src="_content/Blazored.Typeahead/blazored-typeahead.js"></script>

Open “Index.razor” file and replace the following code in a file.

@page "/"
@using Blazored.Typeahead


<BlazoredTypeahead SearchMethod="SearchArticles"
                   @bind-Value="SelectedArticle">
    <SelectedTemplate>
        @context.Title
    </SelectedTemplate>
    <ResultTemplate>
        @context.Title <strong> by @context.Author </strong>
    </ResultTemplate>
</BlazoredTypeahead>

@if (SelectedArticle != null)
{
    <p>Selected Film is: @SelectedArticle.Title</p>
}

@code {

    private List<Article> Articles;
    private Article SelectedArticle;

    protected override void OnInitialized()
    {
        Articles = new List<Article> {
            new Article("CRUD Using Blazor, Entity Framework Core And Dapper", "Faisal Pathan"),
            new Article("Sorting Table In Blazor", "Faisal Pathan"),
            new Article("Refresh Table In Blazor", "Mr. Pathan"),
            new Article("Create Table In Blazor", "Alex Range"),
            new Article("Pagination In Blazor", "The Code Hubs") };
    }

    private async Task<IEnumerable<Article>> SearchArticles(string searchText)
    {
        return await Task.FromResult(Articles.Where(x => x.Title.ToLower().Contains(searchText.ToLower()) ||
        x.Author.ToLower().Contains(searchText.ToLower())).ToList());
    }

    public class Article
    {
        public string Title { get; set; }
        public string Author { get; set; }

        public Article(string title, string author)
        {
            Title = title;
            Author = author;
        }
    }

}

We have done with autocomplete, just press “F5” to run the app and you will get following output.

Recommend articles which you should read once.

  1. CRUD Using Blazor, Entity Framework Core And Dapper
  2. Sorting Table In Blazor
  3. Pagination In Blazor
  4. Searching Feature In Blazor

You can download source code from here.

hope you guys found something useful. Please give your valuable feedback/comments/questions about this article. Please let me know how you like and understand this article and how I could improve it.

Subscribe

Select Categories