【问题标题】:How to use Blazor ValidationMessage on properties made from custom objects如何在由自定义对象创建的属性上使用 Blazor ValidationMessage
【发布时间】:2020-10-23 16:35:38
【问题描述】:

我们如何让 ValidationMessageFor 在验证时包含子对象?

我的课程如下所示:

public class Person
{
    public Person()
    {
        Name = "";
        FavoriteGame = "";
    }

    [Required(ErrorMessage = "Person's name is required and must not be empty.")]
    public string Name { get; set; }

    public string FavoriteGame { get; set; }
}

public class Team
{
    public Team()
    {
        Name = "";
        Game = "";
        Coach = new Person();
    }

    [Required(ErrorMessage = "Team name is required and must not be empty.")]
    public string Name { get; set; }

    public string Game { get; set; }

    public Person Coach { get; set; }
}

我的 Blazor EditForm 看起来像这样:

<EditForm Model="@myTeam" OnValidSubmit="@HandleValidSubmit">
    <DataAnnotationsValidator />
    <ValidationSummary />

    <div class="row p-4">
        <label>Team Name:</label>
        <InputText id="name" @bind-Value="@myTeam.Name" />
        <ValidationMessage For="@(() => myTeam.Name)" />
    </div>

    <div class="row p-4">
        <label>Team Game:</label>
        <InputText id="name" @bind-Value="@myTeam.Game" />
        <ValidationMessage For="@(() => myTeam.Game)" />
    </div>

    <div class="row p-4">
        <label>Coach Name:</label>
        <InputText id="name" @bind-Value="@myTeam.Coach.Name" />
        <ValidationMessage For="@(() => myTeam.Coach.Name)" />
    </div>

    <div class="row p-4">
        <label>Coach's Favorite Game:</label>
        <InputText id="name" @bind-Value="@myTeam.Coach.FavoriteGame" />
        <ValidationMessage For="@(() => myTeam.Coach.FavoriteGame)" />
    </div>

    <div class="row p-4">
        <button type="submit" class="btn btn-success">Submit</button>
    </div>
</EditForm>

但是在运行时,只显示 Team 类中的验证...Person 类的验证被跳过,并且在运行时不会被调用或显示。

是否有一种简单的方法可以让 ValidationMessageFor 为由自定义对象组成的类属性工作,而无需创建全新的自定义验证器或自定义 ValidationMessageFor 组件?

【问题讨论】:

    标签: c# validation blazor data-annotations


    【解决方案1】:

    请在此处查看 blazor 文档: https://docs.microsoft.com/en-gb/aspnet/core/blazor/forms-validation?view=aspnetcore-3.1#nested-models-collection-types-and-complex-types

    基本上你需要在 blazor 表单中使用 ObjectGraphDataAnnotationsValidator 和 [ValidateComplexType] 属性

    【讨论】:

    • 感谢@AppPack 提供了非常简单的解决方案,并为我指明了正确的方向!
    【解决方案2】:

    从@AppPack 指出的文档中学习,这些是完成这项工作所需的唯一更改:

    1. 安装Microsoft.AspNetCore.Components.DataAnnotations.Validation预发布)包

    2. 在复杂属性上使用 [ValidateComplexType]下面的代码示例

      [验证复杂类型] 公共人教练{得到;放; }

    3. 将 Razor 页面中的 DataAnnotationsValidator 替换为 ObjectGraphDataAnnotationsValidator

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-10-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-03-31
      • 1970-01-01
      相关资源
      最近更新 更多