【问题标题】:ASP.NET Core MVC - DataAnnotations localization shows the key name instead of the associated valueASP.NET Core MVC - DataAnnotations 本地化显示键名而不是关联值
【发布时间】:2018-03-12 14:32:30
【问题描述】:

我遇到了一个与在我的 ViewModel 中实现本地化相关的问题,我们使用的是 ASP.NET Core 2.0,这是我尝试过的:

1) 我要翻译 DataAnnotations 消息的视图模型

public class ForgotPasswordViewModel
{
    [Required(ErrorMessage = "RequiredEmail")]
    //[Required(ErrorMessageResourceName = "RequiredEmail", ErrorMessageResourceType = typeof(ForgotPasswordViewModel))]
    [EmailAddress(ErrorMessage = "Veuillez entrer un email valide.")]
    [DataType(DataType.EmailAddress)]
    [Display(Name = "Email")]
    public string Email { get; set; }
}

2) 我添加到 Startup.cs 的代码

public void ConfigureServices(IServiceCollection services){
//...
       services.AddMvc().AddViewLocalization(LanguageViewLocationExpanderFormat.Suffix).AddDataAnnotationsLocalization();
//...
}

public void Configure(IApplicationBuilder app, IHostingEnvironment env){
//...
        var supportedCultures = new[]
        {
            new CultureInfo("en-US"),
            new CultureInfo("fr-FR")
        };

        app.UseRequestLocalization(new RequestLocalizationOptions()
        {
            DefaultRequestCulture = new RequestCulture("fr-FR"),
            SupportedCultures = supportedCultures,
            SupportedUICultures = supportedCultures
        });
//...
}

我有两个资源文件位于 Resources/ViewModels/Account/

  • ForgotPasswordViewModel.fr.resx
  • ForgorPasswordViewModel.en.resx

目前具有以下键/值:

  • RequiredEmail => L'adresse email est necessaire
  • RequiredEmail => 邮件地址是必需的

现在,它不起作用。代替这些消息显示的是“RequiredEmail”,它是键名。

我做错了什么?

【问题讨论】:

  • 请在 48 小时宽限期结束后将其发布为答案并接受它,因为它可能对其他访问者感兴趣。明确鼓励Answering your own question

标签: asp.net-mvc asp.net-core localization viewmodel data-annotations


【解决方案1】:

好吧,我傻了。原始视图模型的路径是 /Models/ViewModels/... 因此,资源文件的路径必须是 Resources/Models/ViewModels/Account/... 而不是 Resources/ViewModels/Account/...

我只是盲目地遵循微软的文档,并没有多想。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-03-27
    • 2021-09-30
    • 2022-06-16
    • 1970-01-01
    • 1970-01-01
    • 2019-01-28
    • 1970-01-01
    相关资源
    最近更新 更多