728x90

데이터 Filter 를 위한 Search 기능을 처리하는 방법입니다.
우선 Search 를 담당할 Search.razor 를 추가합니다.

<section style="margin-bottom: 10px">
    <input type="text" class="form-control" placeholder="Input Search Text" 
           @bind-value="@SearchText" @bind-value:event="oninput" @onkeyup="async () => await OnSearchChanged.InvokeAsync(SearchText)" />
</section>

@code {

    public string? SearchText { get; set; }

    [Parameter]
    public EventCallback<string> OnSearchChanged { get; set; }

}

Parameter 로 EventCallback 를 선언하여 다른곳에서 이벤트를 직접 처리할수 있고
<input> 에 있는 값을 인자로 던지게 됩니다.

FetchData.razor 에서 위 Search.razor 을 삽입하여 사용하는 방법은 아래와 같습니다.

@page "/fetchdata"

<PageTitle>Weather forecast</PageTitle>

@using Blazor.AppTest.Data
@inject WeatherForecastService ForecastService

<h1>Weather forecast</h1>

<p>This component demonstrates fetching data from a service.</p>

<h5>Search Summary</h5>
<Search OnSearchChanged="SearchData" />

@if (forecasts == null)
{
    <p><em>Loading...</em></p>
}
else
{
    <table class="table">
        <thead>
            <tr>
                <th>Date</th>
                <th>Temp. (C)</th>
                <th>Temp. (F)</th>
                <th>Summary</th>
            </tr>
        </thead>
        <tbody>
            @foreach (var forecast in forecasts)
            {
                <tr>
                    <td>@forecast.Date.ToShortDateString()</td>
                    <td>@forecast.TemperatureC</td>
                    <td>@forecast.TemperatureF</td>
                    <td>@forecast.Summary</td>
                </tr>
            }
        </tbody>
    </table>
}

@code {
    private WeatherForecast[]? originForecasts;
    private WeatherForecast[]? forecasts;

    protected override async Task OnInitializedAsync()
    {
        originForecasts = await ForecastService.GetForecastAsync(DateTime.Now);
        forecasts = originForecasts.ToArray();
    }

    private void SearchData(string searchText)
    {
        forecasts = originForecasts?.Where(c => c.Summary.ToUpper().Contains(searchText.ToUpper())).ToArray();
    }
}


<Search OnSearchChanged="SearchData" />
위처럼 이벤트에 SearchData 메서드를 호출하도록 처리하고 인자값으로 Filter 된 데이터를 바인딩하면 됩니다.

실행결과

728x90
Posted by kjun.kr
,