【问题标题】:How localize ErrorMessage in DataAnnotation?如何本地化数据注释中的错误消息?
【发布时间】:2013-12-20 08:50:02
【问题描述】:

使用 MVC 5,我需要为 DataAnnotation 属性本地化 ErrorMessage。 我收到以下错误

错误

属性参数必须是属性参数类型的常量表达式、typeof表达式或数组创建表达式

在模型中

[Compare("Password", ErrorMessage = Resources.Account_Register_ConfirmPasswordErrorMessage)]
public string ConfirmPassword { get; set; }

知道怎么解决吗?

【问题讨论】:

    标签: c# asp.net asp.net-mvc asp.net-mvc-5


    【解决方案1】:

    您需要使用ErrorMessageResourceNameErrorMessageResourceType 属性。

    例如这样:

    [Compare("Password", ErrorMessageResourceName = "ConfirmPasswordErrorMessage",
      ErrorMessageResourceType=typeof(<<type_of_your_resoruce_class>>)]
    public string ConfirmPassword { get; set; }
    

    希望这会有所帮助!

    问候, 乌罗斯

    【讨论】:

    • 这可能有效,但根据此处的 ASP.NET CORE 文档:docs.asp.net/en/latest/fundamentals/…,我们应该能够在不指定资源名称和类型的情况下本地化这些 DataAnnotation 错误消息。然而,无论我尝试什么,我都无法让它发挥作用。有人可以分享一下这方面的经验吗?
    【解决方案2】:

    您不需要任何东西,只需在正确的位置创建资源文件即可。

    例如 Resources > ViewModels > LoginVm.ka-GE.resx(格鲁吉亚文化信息)

    在 LoginVm 中:
    [Required(ErrorMessage = "UserName is Required")]

    LoginVm.ka-GE.resx 中添加

    UserName is Required > სახელი არის აუცილებელი

    一切都完成了。

    【讨论】:

      【解决方案3】:

      Here的详细说明:

      您将适当的文化 resx 文件添加到常规文件夹中,并告诉 DA 引擎查看它们:

      public void ConfigureServices(IServiceCollection services)
      {
          services.AddMvc()
              .AddDataAnnotationsLocalization(options => {
                  options.DataAnnotationLocalizerProvider = (type, factory) =>
                      factory.Create(typeof(SharedResource));
              });
      }
      

      所以对于这个模型:

      public class RegisterViewModel
      {
          [Required(ErrorMessage = "The Email field is required.")]
          [EmailAddress(ErrorMessage = "The Email field is not a valid email address.")]
          [Display(Name = "Email")]
          public string Email { get; set; }
      }
      

      您将在以下位置之一添加 resx 文件:

      • 资源/ViewModels.Account.RegisterViewModel.fr.resx
      • 资源/ViewModels/Account/RegisterViewModel.fr.resx

      对于 WPF、WinForms 等非 ASP.NET 环境,请参阅this 答案。

      【讨论】:

      • 你把两个东西混在一起了。如果您想跨类使用一个文件,则在 ConfigureServices 中注册的 SharedResource 有效。 Resources/ViewModels.Account.RegisterViewModel.fr.resx 可以在您希望为每个类单独翻译的情况下工作(即,您可以在不同的模型中以不同的方式翻译相同的字符串)。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2023-03-13
      • 2021-12-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多