要解决"Aspnet Core MVC验证消息始终可见"的问题,你可以按照以下步骤进行操作:
services.AddMvc()
.AddMvcOptions(options =>
{
options.ModelBindingMessageProvider.SetValueIsInvalidAccessor((x, y) => "输入的值无效");
options.ModelBindingMessageProvider.SetValueMustNotBeNullAccessor((x) => "值不能为空");
options.ModelBindingMessageProvider.SetMissingBindRequiredValueAccessor((x) => "缺少绑定的值");
options.ModelBindingMessageProvider.SetAttemptedValueIsInvalidAccessor((x, y) => "尝试的值无效");
options.ModelBindingMessageProvider.SetMissingKeyOrValueAccessor(() => "缺少密钥或值");
options.ModelBindingMessageProvider.SetUnknownValueIsInvalidAccessor((x) => "未知的值无效");
options.ModelBindingMessageProvider.SetValueMustBeANumberAccessor((x) => "值必须为数字");
});
@model ViewDataDictionary
@if (ViewData.ModelState.IsValid == false)
{
@foreach (var modelState in ViewData.ModelState.Values)
{
foreach (var error in modelState.Errors)
{
- @error.ErrorMessage
}
}
}
@Html.Partial("ValidationMessages")
通过以上步骤,你已经成功地解决了"Aspnet Core MVC验证消息始终可见"的问题。现在,当验证失败时,错误消息将始终显示在页面的顶部。