对于Blazor嵌套组件,您可以try 使用CascadingParameter
和CascadingValue
为子组件提供验证上下文.它允许每个组件参与表单验证并根据上下文显示错误.
Define a CascadingParameter
of type EditContext
in each child component. And register each input's validation within the OnInitialized
method of the child components by calling editContext.AddValidationMessageStore
.
Use DataAnnotationsValidator
or a custom validator to validate the child model. Bind each input to a property of the child component's model.
On the parent component, handle the OnValidSubmit
event to validate all child components.
在Contact
个组成部分中:
@code {
[CascadingParameter]
private EditContext ParentEditContext { get; set; }
protected override void OnInitialized() {
if (ParentEditContext != null) {
// Logic to tie this component's validation to the parent EditContext.
}
}
}
在CreateBill
个组成部分中:
<EditForm EditContext="_editContext" OnValidSubmit="CreateBillOnSubmit">
<CascadingValue Value="_editContext">
<Contact />
<Contact />
<Contact />
<ChargeTerms />
</CascadingValue>
</EditForm>
@code {
private EditContext _editContext;
protected override void OnInitialized() {
_editContext = new EditContext(new CreateBillModel());
}
private void CreateBillOnSubmit() {
// Perform the submission logic here
}
}
请务必在EditContext
上调用Validate
,以在提交时触发对所有子组件的验证.
That would provide a separate validation context for each child component while still being part of the overall form validation. That should eliminate the issue of duplicate error messages and provide contextual feedback to the user.
See also "ASP.NET Core Blazor forms overview".