You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在MudBlazor中为列表添加空值验证提示?

解决方案

直接使用MudBlazor内置的MudValidationMessage组件即可,无需额外添加输入控件,就能触发并显示列表的空值验证错误,步骤如下:

1. 确保FluentValidation集成正确

首先确认项目已注册FluentValidation验证器,并在MudForm内添加FluentValidationValidator组件:

验证器代码

public class ParentModelValidator : AbstractValidator<ParentModel>
{
    public ParentModelValidator()
    {
        RuleFor(parent => parent.productList)
            .NotEmpty()
            .WithMessage("产品列表不能为空");
    }
}

public class ParentModel
{
    public IEnumerable<Product> productList { get; set; } = Enumerable.Empty<Product>();
}

public class Product
{
    public int Id { get; set; }
    public string Name { get; set; }
}

注册验证器(Program.cs)

builder.Services.AddValidatorsFromAssemblyContaining<ParentModelValidator>();
builder.Services.AddMudServices();

2. 在MudForm中使用MudValidationMessage

在表单内添加MudValidationMessage组件,指定For表达式指向你的productList字段,即可显示验证错误:

<MudForm Model="_model">
    <FluentValidationValidator />

    <!-- 你的列表展示、操作按钮等内容 -->
    <MudButton OnClick="AddProduct" Variant="Variant.Outlined">添加产品</MudButton>
    <MudList>
        @foreach (var product in _model.productList)
        {
            <MudListItem>@product.Name</MudListItem>
        }
    </MudList>

    <!-- 核心:显示列表的验证错误 -->
    <MudValidationMessage For="@(() => _model.productList)" Class="text-danger" />

    <MudButton Type="ButtonType.Submit" Variant="Variant.Filled" Class="mt-4">提交</MudButton>
</MudForm>

@code {
    private ParentModel _model = new ParentModel();

    private void AddProduct()
    {
        var newProduct = new Product 
        { 
            Id = _model.productList.Count() + 1, 
            Name = $"产品{_model.productList.Count() + 1}" 
        };
        _model.productList = _model.productList.Append(newProduct);
        StateHasChanged();
    }
}

原理说明

  • MudValidationMessage是MudBlazor专门适配自身表单系统的组件,能自动获取MudForm提供的级联EditContext,不会出现原生BlazorValidationMessage的依赖错误。
  • 只要表单提交时触发验证,该组件就会根据FluentValidation的规则显示对应的错误信息,无需额外绑定输入控件。

内容的提问来源于stack exchange,提问作者Wolfware

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.22 10:41:07