gpt4 book ai didi

c# - 如何使用 Blazor 服务器正确操作 EditContext 中的验证消息

转载 作者:行者123 更新时间:2023-12-05 03:53:02 27 4
gpt4 key购买 nike

我正在将 RazorPages 应用程序转换为 Blazor 服务器呈现,该应用程序实际上只是一个 UI,所有数据访问/操作都是通过 API 完成的。在 CRUD 操作中,API 将以标准化格式返回错误对象的集合。

我在 RazorPages 应用程序中有代码将错误集合转换为 ModelStateDictionary 中的项目,它按预期工作。显示消息,我可以进行更改并重新提交表单。

我已经在 Blazor 应用程序中添加了类似的代码以添加到 EditContext,但我正在努力弄清楚如何清除通过我的扩展方法添加的验证消息。我一直在研究这个问题和所有建议的解决方案,但似乎没有一个对我有用:How to reset custom validation errors when using editform in blazor razor page

这是实际操作 EditContext 的方法:

        private static void AddErrors(EditContext editContext, Dictionary<string, List<string>> errorDictionary)
{
if (errorDictionary != null && errorDictionary.Any())
{
var validationMessageStore = new ValidationMessageStore(editContext);

foreach (var error in errorDictionary)
{
validationMessageStore.Add(editContext.Field(error.Key), error.Value);
}

editContext.NotifyValidationStateChanged();
}
}

这是表单定义:

        <EditForm class="form-signin" OnValidSubmit="OnSubmit" Model="loginModel" Context="CurrentEditContext">
<DataAnnotationsValidator />
<SummaryOnlyValidationSummary />

<div class="form-group">
<InputText id="inputUsername" class="form-control" @bind-Value="loginModel.Username" autofocus placeholder="Username" @onkeyup="@(q => ResetValidation(CurrentEditContext))" />
<ValidationMessage For="@(() => loginModel.Username)" />
</div>

<div class="form-group">
<InputText type="password" id="inputPassword" class="form-control" placeholder="Password" @bind-Value="loginModel.Password" />
<ValidationMessage For="@(() => loginModel.Password)" />
</div>

<div class="form-group">
<button class="btn btn-lg btn-primary btn-block" type="submit">Sign in</button>
</div>
</EditForm>

这是提交表单时的方法签名,传入的 editContext 根据其包含的验证消息显示准确(来自模型属性的 Required 属性的消息是正确的):

protected 异步任务 OnSubmit(EditContext editContext)

SummaryOnlyValidationSummary 是一个自定义组件,它的工作方式与开箱即用的 ValidationSummary 一样,只是它排除了 DataAnnotationsValidator 已经显示的任何消息

我是否以错误的方式添加了消息?如果是这样,是否有关于我哪里出错的好的指导方针?如果没有,有谁知道如何正确清除或重置验证消息?我试图始终提交表单,不仅在它有效时,而且即使强制 editContext.Validate() 也不会清除我的代码添加的验证消息。如果它有帮助,在 ResetValidation 中,我从当前的 editContext 创建一个新的 ValidationMessageStore 实例,它不包含任何消息(虽然不确定预期的行为是什么)。

最佳答案

基于此找到了一个可行的解决方案:

https://remibou.github.io/Using-the-Blazor-form-validation/

我仍在调试以弄清楚为什么当我执行相同的步骤时它会起作用,只是在不同的代码结构中。显然我忽略了一些东西,但它现在起作用了!

编辑 - 我花了一段时间才了解事情并回来更新。

这是我制作的组件,关于从 ApiResult 解析的部分非常适合我的用例,但其余部分非常通用,可以轻松重用:

    public class ServerModelValidator : ComponentBase
{
private ValidationMessageStore _messageStore;

[CascadingParameter] EditContext CurrentEditContext { get; set; }

/// <inheritdoc />
protected override void OnInitialized()
{
if (CurrentEditContext == null)
{
throw new InvalidOperationException($"{nameof(ServerModelValidator)} requires a cascading parameter " +
$"of type {nameof(EditContext)}. For example, you can use {nameof(ServerModelValidator)} inside " +
$"an {nameof(EditForm)}.");
}

_messageStore = new ValidationMessageStore(CurrentEditContext);
CurrentEditContext.OnValidationRequested += (s, e) => _messageStore.Clear();
CurrentEditContext.OnFieldChanged += (s, e) => _messageStore.Clear(e.FieldIdentifier);
}

public void DisplayErrors(Dictionary<string, List<string>> errors)
{
foreach (var err in errors)
{
_messageStore.Add(CurrentEditContext.Field(err.Key), err.Value);
}
CurrentEditContext.NotifyValidationStateChanged();
}

public void DisplayApiErrors<T>(ApiResult apiResult) where T : ValidatedModel
{
if (apiResult != null && apiResult.Errors != null && apiResult.Errors.Any())
{
var errorDictionary = new Dictionary<string, List<string>>();

foreach (var error in apiResult.Errors)
{
var errorKeyPair = error.Message.Count(c => c == '\'') == 2
? GetErrorKeyValuePair(error, typeof(T))
: GetErrorKeyValuePair(error);

// build a dictionary of property, list of validation messages
if (!errorDictionary.ContainsKey(errorKeyPair.Key))
{
errorDictionary.Add(errorKeyPair.Key, new List<string>());
}

errorDictionary[errorKeyPair.Key].Add(errorKeyPair.Value);
}

DisplayErrors(errorDictionary);
}
}


public void DisplayError(string field, string validationMessage)
{
var dictionary = new Dictionary<string, List<string>>
{
{ field, new List<string> { validationMessage } }
};

DisplayErrors(dictionary);
}

private KeyValuePair<string, string> GetErrorKeyValuePair(Error error)
{
return new KeyValuePair<string, string>(string.Empty, error.Message);
}

private KeyValuePair<string, string> GetErrorKeyValuePair(Error error, Type validatedModelType)
{
var splitMessage = error.Message.Split('\'', '\'');

// Find a matching property on T and get it's display name
// if no display name use the property name
// if the property wasn't found use the name from the original error message - this shouldn't ever happen unless there is a property mismatch
var properties = validatedModelType.GetProperties();
var matchedProperty = properties?.FirstOrDefault(p => p.Name == splitMessage[1]);
var displayAttribute = matchedProperty?.GetCustomAttributes(false).FirstOrDefault(a => a.GetType() == typeof(DisplayAttribute)) as DisplayAttribute;
var displayName = (displayAttribute?.Name ?? matchedProperty?.Name) ?? splitMessage[1];

var errorMessage = $"The {displayName} field {splitMessage[2]}.";

return new KeyValuePair<string, string>(splitMessage[1], errorMessage);
}
}

它被放置在任何 EditForm 中:

<EditForm class="modal-form" OnValidSubmit="OnSubmit" Model="_season" Context="CurrentEditContext">
<DataAnnotationsValidator />
<ServerModelValidator @ref="_serverModelValidator" />

<SummaryOnlyValidationSummary />

<EditorWrapper For="@(() => _season.Year)">
<InputNumber id="inputName" class="form-control" @bind-Value="_season.Year" autofocus placeholder="@DisplayName.For(() => _season.Year)" />
</EditorWrapper>


<EditorWrapper For="@(() => _season.Name)">
<InputText id="inputName" class="form-control" @bind-Value="_season.Name" placeholder="@DisplayName.For(() => _season.Name)" />
</EditorWrapper>


<EditorWrapper For="@(() => _season.MaxEventsToScore)">
<InputNumber id="inputMaxEventsToScore" class="form-control" @bind-Value="_season.MaxEventsToScore" placeholder="@DisplayName.For(() => _season.MaxEventsToScore)" />
</EditorWrapper>

<SaveButtonComponent IsSaving="_isProcessing" />
</EditForm>

并在@code block 中声明:

private ServerModelValidator _serverModelValidator;

并像这样使用:

        ApiDataResult<ApiSeason> result;

if (SeasonId.HasValue)
{
// editing
result = await _apiClient.UpdateSeasonAsync(_season.ToApiModel());
}
else
{
// creating
result = await _apiClient.CreateSeasonAsync(_season.ToApiModel());
}

if (result == null)
{
// add an error
_serverModelValidator.DisplayError(string.Empty, "Unknown error occurred, please try again.");
}
else if (result != null && result.HasErrors)
{
// display errors
_serverModelValidator.DisplayApiErrors<SeasonModel>(result);
}

关于c# - 如何使用 Blazor 服务器正确操作 EditContext 中的验证消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61892999/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com