TLDR;如何获得行为
[Required(ErrorMessage = "Le champ {0} est obligatoire")]
Run Code Online (Sandbox Code Playgroud)
虽然只是写作
[Required]
Run Code Online (Sandbox Code Playgroud)
据我了解,该文档没有提供一种隐式本地化一组给定 DataAnnotations 的方法。
我希望有注释的错误消息,例如Required和StringLength可以覆盖而不触及其他人,例如Display并且不需要使用ErrorMessage属性明确指定翻译。
注意:我只需要将消息翻译成法语,因此不需要将解决方案绑定到请求的语言。
我尝试了以下方法:
从这个GitHub 线程
在里面 Startup.cs
services.AddMvc(options => options.ModelBindingMessageProvider.AttemptedValueIsInvalidAccessor =
(value, name) => $"Hmm, '{value}' is not a valid value for '{name}'."));
Run Code Online (Sandbox Code Playgroud)
给了我以下错误
无法分配属性或索引器“DefaultModelBindingMessageProvider.AttemptedValueIsInvalidAccessor”——它是只读的
我找不到任何可以作为这个对象的 setter 的属性。
从这个SO答案
在Startup.cs
services.AddSingleton();
并创建一个类,如跟随
public class LocalizedValidationAttributeAdapterProvider : IValidationAttributeAdapterProvider
{
private readonly ValidationAttributeAdapterProvider _originalProvider = new ValidationAttributeAdapterProvider();
public IAttributeAdapter GetAttributeAdapter(ValidationAttribute attribute, IStringLocalizer stringLocalizer)
{ …Run Code Online (Sandbox Code Playgroud) 我的代码:
启动.cs
public void ConfigureServices(IServiceCollection services)
{
...
services.AddLocalization(options => options.ResourcesPath = "Resources");
services.AddMvc()
.AddViewLocalization(LanguageViewLocationExpanderFormat.Suffix)
.AddDataAnnotationsLocalization(options =>
{
options.DataAnnotationLocalizerProvider = (type, factory) =>
factory.Create(typeof(SharedResource));
});
...
}
Run Code Online (Sandbox Code Playgroud)
共享资源.cs
namespace MyProj.Classes
{
/// <summary>
/// Dummy class to group shared resources
/// </summary>
public class SharedResource
{
}
}
Run Code Online (Sandbox Code Playgroud)
FooViewModel.cs
public class FooViewModel
{
[Required(ErrorMessage = "EmailRequired")]
[EmailAddress(ErrorMessage = "EmailIsNotValid")]
[Display(Name = "Email")]
[DataType(DataType.EmailAddress)]
public string Email { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
FooPage.cshtml
...
<input asp-for="Email" class="form-control">
<div …Run Code Online (Sandbox Code Playgroud) 我想直接更改某些属性(ViewModel的)的显示名称,而无需使用[DisplayName("prop name")]。这应该在返回View之前直接在控制器内部执行,或者在ViewModel类本身内部进行。
我不想更改视图中的任何内容,也不想使用任何数据注释。我该如何实现?
有没有流利的语法可以做到这一点?
我正在使用:ASP.Net Core 2.0
数据注释的问题是我想在运行时获取显示名称(数据注释已预先编译)。
提出此问题的主要原因是找到一种方法来包装IStringLocalizer本地化数据注释时的行为,尤其是其行为。公认的答案很好地说明了这一点。