我正在使用带有Blazor服务器端的.NET 5
我希望在首次显示表单时显示任何验证错误消息(无需提交表单或修改字段(。从我读到的内容来看,这似乎是一种呼唤的语境。Validate((会起作用,但遗憾的是,没有。
下面是一个成对的下页来说明这个问题。
@page "/studentedit"
@using System.ComponentModel.DataAnnotations
<EditForm EditContext="@context">
<DataAnnotationsValidator />
<InputText @bind-Value="@student.FirstName"></InputText>
<ValidationMessage For="@(() => student.FirstName)" />
<button type="submit">Submit</button>
</EditForm>
@code {
private Student student = new Student();
private EditContext context;
protected override async Task OnInitializedAsync()
{
context = new EditContext(student);
context.Validate(); // <--- I thought this would work
await base.OnInitializedAsync();
}
public class Student
{
[Required(ErrorMessage = "First Name is required")]
public string FirstName { get; set; }
}
}
在OnInitialized
上,ValidationMessage
组件尚未实例化,因此无法显示任何验证错误。
在OnAfterRender
中调用EditContext.Validate
是有效的。
@page "/studentedit"
@using System.ComponentModel.DataAnnotations
<EditForm EditContext="@context">
<DataAnnotationsValidator />
<InputText @bind-Value="@student.FirstName"></InputText>
<ValidationMessage For="@(() => student.FirstName)" />
<button type="submit">Submit</button>
</EditForm>
@code {
private Student student = new Student();
private EditContext context;
protected override void OnInitialized()
{
context = new EditContext(student);
base.OnInitializedAsync();
}
protected override void OnAfterRender(bool firstRender)
{
if (firstRender)
context.Validate();
}
public class Student
{
[Required(ErrorMessage = "First Name is required")]
public string FirstName { get; set; }
}
}