要解决此问题,您可以添加<option value="">Select...</option>
在你的代码中是这样的:
<InputSelect @bind-Value="partner.PartnerCategoryId">
@if (categoryList != null)
{
<option value="">Select...</option>
@foreach (var item in categoryList.OrderBy(x => x.PartnerCategoryId))
{
<option value="@item.PartnerCategoryId">@item.Name</option>
}
}
</InputSelect>
而在你的PartnerCategory
模型根据需要定义 PartnerCategoryId。请注意,PartnerCategoryId 的类型可为 null:int?
[Required]
public int? PartnerCategoryId {get; set;}
除非用户选择了一个值,否则这将阻止“提交”您的表单
要测试新的更改:
添加OnValidSubmit
归因于你的EditForm
组件并将其值设置为“HandleValidSubmit
"
Add a HandleValidSubmit
方法,像这样:
private void HandleValidSubmit()
{
// Put code here to save your record in the database
}
在 EditForm 底部添加一个提交按钮:
<p><button type="submit">Submit</button></p>
运行您的应用程序,然后点击“Submit
“按钮...正如您所看到的,表单未“提交”,并且选择元素的边框被涂成红色。
这是代码的完整版本:
<EditForm Model="@partner" OnValidSubmit="HandleValidSubmit">
<InputSelect @bind-Value="partner.PartnerCategoryId">
@if (categoryList != null)
{
<option value="">Select...</option>
@foreach (var item in categoryList.OrderBy(x => x.PartnerCategoryId))
{
<option value="@item.PartnerCategoryId">@item.Name</option>
}
}
</InputSelect>
<p><button type="submit">Submit</button></p>
</EditForm>
@code {
Partner partner = new Partner();
private IEnumerable<PartnerCategory> categoryList;
protected override async Task OnInitializedAsync()
{
categoryList = await CategoryService.GetAllAsync();
}
private void HandleValidSubmit()
{
Console.WriteLine("Submitted");
}
}