Search code examples
c#blazormudblazor

MudBlazor: MudTable filtering not working


Project created through VS2022's "Blazor Web App" template and I've installed MudBlazor.

I've copied this filterable Table example from the MudBlazor docs almost exactly: https://mudblazor.com/components/table#table-with-pagination-and-filtering

Still can't get the filter event to trigger on key presses in the text field, event is only raised on page refresh. Starting to suspect it could be related to the render mode? The pagination isn't working either.

@page "/"
@rendermode InteractiveServer
@inject StockService StockService
@using StockSim.API.Models
@using StockSim.API.Services

<MudTable Items="@Stocks" Dense="true" Hover="true" Striped="true" Filter="new Func<Stock,bool>(FilterFunc1)">
    <ToolBarContent>
        <MudText Typo="Typo.h6">Stocks</MudText>
        <MudSpacer />
        <MudTextField @bind-Value="searchString1" Placeholder="Search" Adornment="Adornment.Start" AdornmentIcon="@Icons.Material.Filled.Search" IconSize="Size.Medium" Class="mt-0"></MudTextField>
    </ToolBarContent>
    <HeaderContent>
        <MudTh>Symbol</MudTh>
        <MudTh>Name</MudTh>
    </HeaderContent>
    <RowTemplate>
        <MudTd DataLabel="Symbol">@context.Symbol</MudTd>
        <MudTd DataLabel="Name">@context.Name</MudTd>
    </RowTemplate>
    <PagerContent>
        <MudTablePager />
    </PagerContent>
</MudTable>


@code {
    private string searchString1 = "";
    private IEnumerable<Stock> Stocks = new List<Stock>();

    protected override async Task OnInitializedAsync()
    {
        Stocks = await StockService.GetStocksAsync();
    }

    private bool FilterFunc1(Stock Stock) => FilterFunc(Stock, searchString1);

    private bool FilterFunc(Stock Stock, string searchString)
    {
        if (string.IsNullOrWhiteSpace(searchString))
            return true;
        if (Stock.Symbol.Contains(searchString, StringComparison.OrdinalIgnoreCase))
            return true;
        if (Stock.Name.Contains(searchString, StringComparison.OrdinalIgnoreCase))
            return true;
        return false;
    }
}


Solution

  • I reviewed the docs (https://learn.microsoft.com/en-us/aspnet/core/blazor/components/render-modes?view=aspnetcore-9.0#apply-a-render-mode-to-the-entire-app) and apparently had to add @rendermode="InteractiveServer" to the Routes and HeadOutlet elements in App.razor. I'm not entirely sure why this fixed it since my .razor was already using @rendermode InteractiveServer locally. Perhaps the rendermode needed to be set globally like that to support MudBlazor's components too? Not sure.