本地化数据注释默认消息([必需] [StringLength]等)

Omu*_*Omu 21 asp.net-mvc localization data-annotations

如果我用这样的属性装饰我的ViewModels的属性:

public class Vm
{

[Required]
[StringLength(35)]
public string Name {get;set;}

}
Run Code Online (Sandbox Code Playgroud)

我将获得英语验证消息:

"this field is required"
"The field Name must be a string with a maximum length of 35"
Run Code Online (Sandbox Code Playgroud)

我怎么能翻译它们?

Dar*_*rov 37

您可以使用该ErrorMessageResourceName属性:

[Required(ErrorMessageResourceName = "SomeResource")]
[StringLength(30, ErrorMessageResourceName = "SomeOtherResource")]
public string Name { get; set; }
Run Code Online (Sandbox Code Playgroud)

您可以查看此博客文章以获取示例.


更新:

Application_Start:

DefaultModelBinder.ResourceClassKey = "Messages";
Run Code Online (Sandbox Code Playgroud)

Messages.resx文件中,您需要添加自定义错误消息.使用Reflector查看System.Web.MvcSystem.ComponentModel.DataAnnotations程序集以查看要使用的键名.

  • 原来如此.您正在尝试本地化默认错误消息.我担心除非你安装.NET框架的本地化版本,否则这是不可能的.我建议您在每个属性中指定错误消息,并具有处理这些消息的自定义资源文件. (4认同)
  • 我想更改默认消息而不为每个属性指定它,我曾经看到你必须在App_GlobalResources中有一个Messages.resx,但我不知道每条消息的密钥 (2认同)

Man*_*jua 10

现在使用asp.net MVC 3有一个更好的解决方案,因为有人正在寻找更新,更好的方法.

http://blog.gauffin.org/2011/09/easy-model-and-validation-localization-in-asp-net-mvc3/

例如:

public class UserViewModel
{
    [Required(ErrorMessageResourceName = "Required", ErrorMessageResourceType = typeof(Resources.LocalizedStrings))]
    [LocalizedDisplayName(ErrorMessageResourceName = "UserId", ErrorMessageResourceType = typeof(Resources.LocalizedStrings))]
    [LocalizedDescription(ErrorMessageResourceName = "UserIdDescription", ErrorMessageResourceType = typeof(Resources.LocalizedStrings))]
    public int Id { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

SO相关问题 - Mvc 3.0 DataAnnotations本地化