如果我在将表单中的数据保存到数据库时遇到异常,我想向用户显示该错误。最简单的方法是使用适当的消息调用 ValidationMessageStore.Add()。
但是,Add() 的第一个参数是 FieldIdentifier 对象。由于这不是已提交的特定问题,我应该通过什么?
谢谢 - 戴夫
尝试添加到 ValidationMessageStore 是错误的方法。网上有很多帖子展示了如何这样做,但所有帖子都非常复杂,这通常表明这是错误的方法。在这种情况下是。
使用 CustomValidation 元素很容易实现。这就是它的设计目的,它在显示的验证问题中看起来是一样的。
第一步,添加文件CustomValidation.cs(我放在Shared)。 我从微软文档中得到这段代码.
// 来自 https://learn.microsoft.com/en-us/aspnet/core/blazor/forms-and-input-components?view=aspnetcore-7.0
using Microsoft.AspNetCore.Components;
using Microsoft.AspNetCore.Components.Forms;
namespace LouisHowe.web.Shared
{
public class CustomValidation : ComponentBase, IDisposable
{
private ValidationMessageStore? messageStore;
[CascadingParameter]
private EditContext? CurrentEditContext { get; set; }
protected override void OnInitialized()
{
if (CurrentEditContext is null)
{
throw new InvalidOperationException(
$"{nameof(CustomValidation)} requires a cascading " +
$"parameter of type {nameof(EditContext)}. " +
$"For example, you can use {nameof(CustomValidation)} " +
$"inside an {nameof(EditForm)}.");
}
messageStore = new(CurrentEditContext);
CurrentEditContext.OnValidationRequested += CurrentEditContext_OnValidationRequested;
CurrentEditContext.OnFieldChanged += CurrentEditContext_OnFieldChanged;
}
private void CurrentEditContext_OnValidationRequested(object? sender, ValidationRequestedEventArgs e)
{
messageStore?.Clear();
}
private void CurrentEditContext_OnFieldChanged(object? sender, FieldChangedEventArgs e)
{
messageStore?.Clear(e.FieldIdentifier);
}
public void DisplayErrors(Dictionary<string, List<string>> errors)
{
if (CurrentEditContext is not null)
{
foreach (var err in errors)
{
messageStore?.Add(CurrentEditContext.Field(err.Key), err.Value);
}
CurrentEditContext.NotifyValidationStateChanged();
}
}
public void ClearErrors()
{
messageStore?.Clear();
CurrentEditContext?.NotifyValidationStateChanged();
}
/// <inheritdoc />
public void Dispose()
{
if (CurrentEditContext != null)
{
CurrentEditContext.OnValidationRequested -= CurrentEditContext_OnValidationRequested;
CurrentEditContext.OnFieldChanged -= CurrentEditContext_OnFieldChanged;
}
}
}
}
第 2 步,将 CustomValidation 添加到您的 .razor(这里的示例使用 DevExpress):
<EditForm Model="@RegisterPageModel" OnValidSubmit="HandleValidSubmitAsync" Context="EditFormContext">
<DataAnnotationsValidator/>
<CustomValidation @ref="customValidation" />
<DxFormLayout>
第 3 步,将以下内容添加到您的剃刀页面代码中:
private CustomValidation? customValidation;
// ...
async Task HandleValidSubmitAsync(EditContext editContext)
{
customValidation?.ClearErrors();
// ...
if (error)
customValidation?.DisplayErrors(errors);
更新: h/t to @MrCakaShaunCurtis,添加到 Dispose() 功能中。