我正在将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 async Task OnSubmit(EditContext editContext)
SummaryOnlyValidationSummary是一个自定义组件,其作用类似于开箱即用的ValidationSummary,但它排除了DataAnnotationsValidator已经显示的任何消息
我添加消息的方式错误吗?如果是这样,是否有关于我哪里出错的良好指导?如果不是,是否有人知道如何正确清除或重置验证消息?我试图总是提交表单,不仅在表单有效时,甚至强迫editContext.Validate()都不会清除代码中添加的验证消息。如果有什么帮助,请在ResetValidation中,在当前editContext之外创建一个新的ValidationMessageStore实例,该实例不包含任何消息(不确定期望的行为是什么)。
答案 0 :(得分:0)
基于此找到了可行的解决方案:
https://remibou.github.io/Using-the-Blazor-form-validation/
我仍在调试以弄清楚为什么当我执行相同的步骤(只是在不同的代码结构中)时,该方法能起作用。显然,我忽略了某些内容,但现在可以正常使用了!
edit -花了我一段时间才了解最新情况,然后再进行更新。
这是我制作的组件,有关从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块中声明:
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);
}