简体   繁体   English

如何本地化 DataAnnotation 中的 ErrorMessage?

[英]How localize ErrorMessage in DataAnnotation?

Using MVC 5 I need to localize an ErrorMessage for a DataAnnotation attributes.使用 MVC 5 我需要本地化 DataAnnotation 属性的 ErrorMessage。 I receive the following error我收到以下错误

ERROR错误

An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type属性参数必须是属性参数类型的常量表达式、typeof 表达式或数组创建表达式

In model在模型中

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

Any idea how to fix it?知道如何修复它吗?

You need to use ErrorMessageResourceName and ErrorMessageResourceType properties.您需要使用ErrorMessageResourceNameErrorMessageResourceType属性。

For example like this:例如像这样:

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

Hope this helps!希望这有帮助!

Regards, Uros问候,乌罗斯

You don't need anything, just create your resource file in right place.您不需要任何东西,只需在正确的位置创建您的资源文件。

For example Resources > ViewModels > LoginVm.ka-GE.resx (Georgian culture-info)例如资源> ViewModels > LoginVm.ka-GE.resx (格鲁吉亚文化信息)

in LoginVm:在登录虚拟机中:
[Required(ErrorMessage = "UserName is Required")]

and in LoginVm.ka-GE.resx just add并在LoginVm.ka-GE.resx 中添加

UserName is Required > სახელი არის აუცილებელი < (it's Georgian Language) UserName is Required > სახელი არის აუცილებელი <(这是格鲁吉亚语)

and all done.并全部完成。

Here 'sa detailed explanation on how to do this: 是有关如何执行此操作的详细说明:

You add appropriate culture resx files to conventional folders, and tell the DA engine to look through them:您将适当的文化 resx 文件添加到常规文件夹,并告诉 DA 引擎查看它们:

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

So for this model:所以对于这个模型:

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; }
}

You'd add a resx file in one of the following locations:您将在以下位置之一添加 resx 文件:

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

For non-ASP.NET environments such as WPF, WinForms or others, see this answer.对于 WPF、WinForms 等非 ASP.NET 环境,请参阅答案。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM