正如标题所述,我正在尝试实现一个 Fluentsearch 输入框,该输入框具有一个 oninput 事件,每次用户在输入中键入内容时都会触发 SearchEmployees 方法。由于未知原因,输入框不允许我输入任何内容。基本上,当我输入击键时,它会清除输入框,不允许我在其中输入任何内容。我确实注意到,如果我使用 bind-value:after 指令并将 SearchEmployees 分配给它,它就可以工作,问题是我不希望用户必须按 Enter 键才能触发该方法,我希望它出现在每个按键
@page "/Sandbox"
@inject IDbContextFactory<SFSChecklistContext> _contextFactory
@using Microsoft.AspNetCore.Components.Web
<AuthorizeView Policy="SuperAdmin">
<Authorized>
<!-- Input field with searchEmployees method -->
</Authorized>
<NotAuthorized>
<FluentSearch @ref=searchTest
@bind-Value="@inputValue"
Placeholder="Search for Employee"
@oninput="SearchEmployees"
/>
<br />
<ul>
@foreach (var employee in FilteredEmployees)
{
<li>@employee.FirstName @employee.LastName</li>
}
</ul>
<p>
You searched for: @inputValue
</p>
</NotAuthorized>
</AuthorizeView>
@code {
private string? inputValue;
private bool isSearching;
private FluentSearch? searchTest;
private List<Employee> FilteredEmployees { get; set; } = new List<Employee>();
protected override async Task OnInitializedAsync()
{
await base.OnInitializedAsync();
}
private async Task SearchEmployees()
{
if (!string.IsNullOrWhiteSpace(inputValue))
{
using (var _context = await _contextFactory.CreateDbContextAsync())
{
EmployeeRepo repo = new EmployeeRepo(_context);
FilteredEmployees = await repo.SearchEmployeesAsync(inputValue);
}
}
else
{
FilteredEmployees.Clear();
}
// Update the UI after the search operation
StateHasChanged();
}
}
我尝试实现 oninput 和 bind-value:after 指令,我希望用户在输入字段中输入内容时能够看到 UL 更改的结果
你的问题是你没有正确绑定。
这是代码的重构版本,我相信它的行为符合您的预期。
注:
Immediate
是设置控件在每次击键时更新的 FluentUI 方法。after
在 inputValue
已被绑定更新并执行搜索后被调用。StateHasChanged
,绑定更新的 UI 处理程序已内置。@page "/"
<PageTitle>Home</PageTitle>
<h1>Hello, world!</h1>
Welcome to your new Fluent Blazor app.
<FluentSearch @ref=searchTest
@bind-Value="@inputValue"
Immediate
@bind-Value:after="SearchEmployees"
Placeholder="Search for Employee" />
<br />
<ul>
@foreach (var employee in FilteredEmployees)
{
<li>@employee.FirstName @employee.LastName</li>
}
</ul>
<p>
You searched for: @inputValue
</p>
@code {
private string? inputValue;
private bool isSearching;
private FluentSearch? searchTest;
private List<Employee> FilteredEmployees { get; set; } = new List<Employee>();
private async Task SearchEmployees()
{
if (!string.IsNullOrWhiteSpace(inputValue))
{
// Fake an async data call
await Task.Delay(10);
this.FilteredEmployees = this.Employees
.Where(item => item.FullName.Contains(inputValue, StringComparison.CurrentCultureIgnoreCase))
.ToList();
}
else
FilteredEmployees.Clear();
// not required
//StateHasChanged();
}
public record Employee(string FirstName, string LastName)
{
public string FullName => $"{FirstName} {LastName}";
}
private List<Employee> Employees = new()
{
new("Fred", "Bloggs"),
new("Fred", "Smith"),
new("John", "Smith"),
};
}