使用Blazor中的选择框筛选数据列表



我有一个名为SchoolsTable的表,其中有一个视图将显示已输入的所有记录。这是我的型号:

public partial class SchoolsTable
{
public int Id{ get; set; }
public int Name{ get; set; }
public int State{ get; set; }
}

我想做的是在该视图中有一个下拉列表,让我选择一个状态,并且视图上显示的数据将仅为具有相应状态的数据。

剃须刀组件:

<table style="width:50%; margin-left:710px; border:1px solid black" border="1" class="table-bordered">
<tr bgcolor="#ffffff" style="border:1px solid black">
<th style="border:1px solid black">Schools</th>
@foreach (var item in school)
{         
<th style="border:1px solid black">@item.Name</th>
<th style="border:1px solid black">@item.State</th>
}
</tr>
</table>
@code{
private List<SchoolTable> schools=new List <SchoolTable>();
private SchoolTable school= new SchoolTable();
protected override async Task OnInitializedAsync()
{
GetSchoolTable();
}
private List<SchoolTable> GetSchoolTable()
{
schools= SchoolService.GetSchoolTable();
return schools;
}
}

select将所有状态作为副本:

<label for="State">Choose a State:</label>
<select name="State">
@foreach (var item in schools)
{
<option value="@item.State">@item.State</option>
}
</select>

另外,我创建了一个状态表,其中有两条记录:

public partial class StatesTable
{
public int Id{ get; set; }
public int Description{ get; set; }
}

使用此选择,将状态作为单个状态,而不是重复状态

<label for="State">Choose a State:</label>
<select name="State">
@foreach (var item in branch)
{
<option value="@item.Id">@item.Description</option>
}
</select>

您需要做几件事。

首先,您需要将<select>元素的选定值绑定到一个字段。为此,您需要使用@bind属性:

<label for="State">Choose a State:</label>
<select id="State" @bind="selectedState">
<option value="">Choose a state</option>
@foreach (var item in branch)
{
<option value="@item.Id">@item.Description</option>
}
</select>
@code {
private int? selectedState;
}

另外,在select中添加一个空值选项,这样默认情况下就不会选择任何状态:

<option value="">Choose a state</option>

现在,您可以创建一个属性,根据所选状态返回筛选的学校:

private List<SchoolTable> FilteredSchools => selectedState.HasValue ?
schools.Where(s => s.State == selectedState.Value).ToList() :
schools;

使用此属性生成<table>元素内容:

<label for="State">Choose a State:</label>
<select id="State" @bind="selectedState">
<option value="">Choose a state</option>
@foreach (var item in branch)
{
<option value="@item.Id">@item.Description</option>
}
</select>
<table style="width:50%; margin-left:710px; border:1px solid black" border="1" class="table-bordered">
<tr bgcolor="#ffffff" style="border:1px solid black">
<th style="border:1px solid black">Schools</th>
@foreach (var item in FilteredSchools)
{         
<th style="border:1px solid black">@item.Name</th>
<th style="border:1px solid black">@item.State</th>
}
</tr>
</table>
@code{
private List<SchoolTable> schools = new List<SchoolTable>();
private int? selectedState;
private List<SchoolTable> FilteredSchools => selectedState.HasValue ?
schools.Where(s => s.State == selectedState.Value).ToList() :
schools;
protected override void OnInitialized()
{
schools = SchoolService.GetSchoolTable();
}
}

相关内容

  • 没有找到相关文章