我正在Blazor(.net 8)中设计一个组件,其中包含许多子组件.请参见下图:

The CreateBill component, with child Contact and ChargeTerms components

  • CreateBill组件是主容器
  • Contact组件有3个实例
  • 有一个ChargeTerms分量的单数实例

目前,我的应用程序有一个提交按钮(屏幕外),它可以一次对整个模型执行验证:

<EditForm EditContext="_editContext" OnValidSubmit="CreateBillOnSubmit">

这样做的缺点是,模型上的任何验证失败都只作为一个大列表返回,并且没有它们所来自的特定组件的任何上下文.例如,如果所有联系人表单都为空,则它们都不会突出显示,并且所有验证错误都会重复3次(如下所示)

Duplicate error messages

我不确定嵌套验证的模式应该是什么,因为根对象上只有一个<Form>,子组件(Contact、Charge Term)不包含表单,只有<InputText>之类的内容.

是否有建议的模式来显示每个字段的验证错误?

推荐答案

对于Blazor嵌套组件,您可以try 使用CascadingParameterCascadingValue为子组件提供验证上下文.它允许每个组件参与表单验证并根据上下文显示错误.

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".

Csharp相关问答推荐

C#使用属性和值将JSON转换为XML

. net依赖注入如何避免服务类中的新

更新产品但丢失产品ASP.NET Core的形象

模型绑定RazorPage表单

如何使datagridview的列具有响应性,以便不是所有列都更改其宽度

Mongo作为.NET中Testcontainers的副本集

C#使用TextFieldParser读取.csv,但无法使用";0";替换创建的列表空条目

每个http请求需要60秒,为什么?

集合表达式没有目标类型

在C#中反序列化/序列化具有混合元素顺序的XML时出现问题

如何在C#中转换泛型包装类内部的派生类

从另一个不同 struct 的数组创建Newtonsoft.Json.Linq.J数组

如何防止Visual Studio断点以红色突出显示到整行?

.NET 6:如何防止系统生成的日志(log)?

.NET8Blazor-为什么Rapzor渲染在for循环之后显示?

类/值和日期的泛型方法

用于ASP.NET核心的最小扩展坞

Blazor服务器项目中的Blazor/.NET 8/Web API不工作

从HTML元素获取 colored颜色

在使用.NET EF Core DbContext属性之前,是否应使用null判断