Dar*_*gan 3 client localization data-annotations webassembly blazor
Asp.net core 服务器端本地化有很好的文档记录并且对我有用。但是,如何在 Blazor WebAssembly 客户端上本地化 DTO 模型上的 DataAnnotations?
在服务器端,我添加了下面的代码,并且 DataAnnotations 已本地化。一切都按预期进行。
...
services
.AddRazorPages() .AddViewLocalization(Microsoft.AspNetCore.Mvc.Razor.LanguageViewLocationExpanderFormat.Suffix)
.AddDataAnnotationsLocalization(
options =>
{
options.DataAnnotationLocalizerProvider = (type, factory) =>
{
return factory.Create(typeof(CommonStrings));
};
});
...
Run Code Online (Sandbox Code Playgroud)
但是我如何在 Blazor 客户端(WebAssembly)上做同样的事情呢?例如,我有一个位于客户端的模型:
public class ApplicationUserDTO
{
public string Id { get; set; }
[Required(ErrorMessage ="Field {0} is required")]
[Display(Name ="First name")]
public string FirstName { get; set; }
[Required]
[Display(Name = "Last name")]
public string LastName { get; set; }
[Required]
[Display(Name = "Email")]
public string Email { get; set; }
[Required]
[Display(Name = "Username")]
public string Username { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
我想通过<EditForm>
组件将其发布到后端,然后在执行此操作之前在客户端进行验证。我也想像在 aspnet.core 服务器上一样本地化它 - 错误/验证消息和显示名称...
我尝试使用 LocalizedValidator 组件:
public class MessageValidatorBase<TValue> : ComponentBase, IDisposable
{
private FieldIdentifier _fieldIdentifier;
private EventHandler<ValidationStateChangedEventArgs> _stateChangedHandler
=> (sender, args) => StateHasChanged();
[CascadingParameter]
private EditContext EditContext { get; set; }
[Parameter]
public Expression<Func<TValue>> For { get; set; }
[Parameter]
public string Class { get; set; }
protected IEnumerable<string> ValidationMessages =>
EditContext.GetValidationMessages(_fieldIdentifier);
protected override void OnInitialized()
{
_fieldIdentifier = FieldIdentifier.Create(For);
EditContext.OnValidationStateChanged += _stateChangedHandler;
}
public void Dispose()
{
EditContext.OnValidationStateChanged -= _stateChangedHandler;
}
}
Run Code Online (Sandbox Code Playgroud)
然后创建组件:
@typeparam TValue
@inherits MessageValidatorBase<TValue>
@inject StringLocalizationService _localizer
@foreach (var message in ValidationMessages)
{
<div class="@Class">
@_localizer[message]
</div>
}
Run Code Online (Sandbox Code Playgroud)
但问题是我已经在这里得到了扩展的字符串。例如,如果我收到这样的错误消息“字段 {0} 是必需的”,我会收到“字段名字是必需的”,该消息不会被本地化,因为我没有带有该键的资源,而且我不打算为每个属性名称翻译相同的错误消息...
[编辑]我只是想知道是否有一些琐碎的事情我没有做,而不是完全自己实现它
[MaxLength(5, ErrorMessageResourceName = "LengthError", ErrorMessageResourceType = typeof(Resources.App))]
public string Prefix { get; set; }
Run Code Online (Sandbox Code Playgroud)
在您的客户端中创建一个名为 Resources 的文件夹。为每种语言添加一个“.resx”文件以及默认值(无语言)。
归档时间: |
|
查看次数: |
2965 次 |
最近记录: |