如何解决如何在自定义对象制成的属性上使用Blazor ValidationMessage
在验证时,如何使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组件?
解决方法
请在此处查看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指向的文档中学习,这些是完成此工作所需的唯一更改:
-
安装 Microsoft.AspNetCore.Components.DataAnnotations.Validation ( prerelease )软件包
-
在复杂属性上使用 [ValidateComplexType] (下面的代码示例)
[ValidateComplexType] 公共人员教练组; }
在剃刀页面中用 ObjectGraphDataAnnotationsValidator -
替换DataAnnotationsValidator
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。