localize data annotations default messages ([Required] [StringLength] etc.)

回眸只為那壹抹淺笑 提交于 2019-11-28 16:49:23

问题


if I decorate the properties of my ViewModels with attributes like this:

public class Vm
{

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

}

I am going to get english validation messages:

"this field is required"
"The field Name must be a string with a maximum length of 35"

how could I translate them ?


回答1:


You could use the ErrorMessageResourceName property:

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

You may checkout this blog post for an example.


UPDATE:

In Application_Start:

DefaultModelBinder.ResourceClassKey = "Messages";

And in the Messages.resx file you need to add the custom error messages. Use Reflector to look at the System.Web.Mvc and System.ComponentModel.DataAnnotations assemblies in order to see the key names to use.




回答2:


There is a much better solution using asp.net MVC 3 these days incase someone is looking for a newer and far better approach.

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

For example:

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

SO related question - Mvc 3.0 DataAnnotations Localization



来源:https://stackoverflow.com/questions/3758512/localize-data-annotations-default-messages-required-stringlength-etc

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!