[英]Getting values from table in a Select box in Blazor
我的 Blazor 項目中有一個 select 框,它使用 MudBlazor 來處理 select 框等組件,我正在嘗試創建一個表單來注冊員工。 我想以這種形式提取一個branch
表,以便用戶可以從下拉列表中選擇一個分支並將該值發送到具有分支列的register employees
表。 問題是 select 框在單擊時不顯示任何值。 它只顯示一個小的空白矩形。 有誰知道我做錯了什么?
Razor 頁面:
<MudSelect @bind-Value="employee.Branch" For="@(()=>employee.Branch)" T="string" Label="Branch name" AnchorOrigin="Origin.BottomCenter" Required="true">
@foreach (var branch in branch)
{
<MudSelectItem Value="@branch.Id">@branch.Description</MudSelectItem>
}
</MudSelect>
@code{
private List<Branches> branch = new List<Branches>();
private Branches branches = new Branches();
private List<Branches> GetBranches(string Id)
{
branch=employeeService.GetBranches(Id);
return branch;
}
}
員工服務.cs:
public List<Branches> GetBranches(string Id)
{
return _dbContext.Branches.Where(x => x.Id == Id).ToList();
}
問題是你的循環是錯誤的
@foreach (var **branch** in branch)
而不是 Var 分支使用其他名稱,因為您的 Collection name 和 Item name and collection 是相同的分支使用 Item
<MudSelect @bind-Value="employee.Branch" For="@(()=>employee.Branch)" T="string" Label="Branch name" AnchorOrigin="Origin.BottomCenter" Required="true">
@foreach (var item in branch)
{
<MudSelectItem Value="@item.Id">@item.Description</MudSelectItem>
}
</MudSelect>
protected override void OnInitialized()
{
GetBranches(with your id );
}
如果它作為參數出現,那么您需要使用“SetParametersAsync”事件
檢查生命周期
由於您沒有顯示太多上下文,因此這是您的代碼的修改版本:
服務和數據類
public class EmployeeService
{
public async ValueTask<IEnumerable<Branch>> GetBranchesAsync(string Id)
{
// Emulate an async data get
await Task.Delay(100);
return new List<Branch>
{
new Branch { Id = "F", Description = "France"},
new Branch { Id = "UK", Description = "United Kingdom"},
new Branch { Id = "P", Description = "Portugal"},
};
}
}
public class Branch
{
public string Id { get; set; } = string.Empty;
public string Description { get; set; } = string.Empty;
}
public class Employee
{
public string Id { get; set; } = string.Empty;
public Branch Branch { get; set; } = new Branch();
}
頁:
@page "/"
@inject EmployeeService employeeService
<PageTitle>Index</PageTitle>
<MudSelect @bind-Value="employee.Branch.Id" Label="Branch name" AnchorOrigin="Origin.BottomCenter" Required="true">
@foreach (var branch in branches)
{
<MudSelectItem Value="@branch.Id">@branch.Description</MudSelectItem>
}
</MudSelect>
@code {
private IEnumerable<Branch> branches = Enumerable.Empty<Branch>();
private Branch branch = new Branch();
private Employee employee = new Employee();
protected async override Task OnInitializedAsync()
{
branches = await employeeService.GetBranchesAsync(string.Empty);
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.