Search code examples
asp.net-coreblazor-server-sidefluent-ui

Blazor Fluent UI AutoComplete not working


I'm trying to get the Fluent UI Autocomplete wired up to some demo data. I used the template creator to new up a project and I'm practically copying and pasting the example code and nothing is happening.

@page "/"

<PageTitle>Home</PageTitle>

<FluentAutocomplete TOption="Country"
                    AutoComplete="off"
                    Autofocus="true"
                    Label="Select a country"
                    Width="250px"
                    Placeholder="Select countries"
                    OnOptionsSearch="@OnSearchAsync"
                    OptionText="@(item => item.Name)"
                    @bind-SelectedOptions="@SelectedItems" />

<p>
    <b>Selected</b>: @(String.Join(" - ", SelectedItems.Select(i => i.Name)))
</p>

@code
{

  protected List<Country> Countries = new List<Country>
  {
    new Country {Name = "whatever", Code ="wh"}, 
    new Country {Name = "somewhere", Code = "so"}
  };

  IEnumerable<Country> SelectedItems = Array.Empty<Country>();

  private async Task OnSearchAsync(OptionsSearchEventArgs<Country> e)
  {
    e.Items = Countries.Where(i => i.Name.Contains(e.Text, StringComparison.OrdinalIgnoreCase)).ToArray();
  }

  public class Country
  {
    public string Code { get; set; }
    public string Name { get; set; }
  }
}

I've got the necessary configuration lines in Program.cs.

using Microsoft.FluentUI.AspNetCore.Components;
using FluentUIDemo.Components;
using FluentUIDemo.Services;
using FluentUIDemo;
using Microsoft.EntityFrameworkCore;

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.
builder.Services.AddRazorComponents()
.AddInteractiveServerComponents();

builder.Services.AddHttpClient();

builder.Services.AddFluentUIComponents();

builder.Services.AddScoped<IMailService, MailService>();


var app = builder.Build();

Solution

  • I tested through directly creating a project in VS and the difference between project template and my approach is that render mode not applied in template project in Apps.razor.

    You need to add the code in component to apply the render mode.

    @page "/"
    
    @rendermode InteractiveServer
    
    <PageTitle>Home</PageTitle>
    ...
    

    enter image description here

    You can refer to the document to get more details. https://learn.microsoft.com/en-us/aspnet/core/blazor/components/render-modes?view=aspnetcore-8.0