MVC3按属性名称的本地化显示名称属性

时间:2013-05-23 10:30:37

标签: c# asp.net-mvc resources data-annotations

我最近学习了如何使用以下文章为我的模型属性创建本地化显示名称:Simplified localization for DataAnnotations

我现在试图通过从构造函数中删除参数来进一步推动它。 意思不是拥有这个

public class User
{
    [Required]
    [LocalizedDisplayNameAttribute("User_Id")]
    public int Id { get; set; }

    [Required]
    [StringLength(40)]
    [LocalizedDisplayNameAttribute("User_FirstName")]
    public string FirstName { get; set; }

    [Required]
    [StringLength(40)]
    [LocalizedDisplayNameAttribute("User_LastName")]
    public string LastName { get; set; }
}

我想要这个

public class User
{
    [Required]
    [LocalizedDisplayNameAttribute]
    public int Id { get; set; }

    [Required]
    [StringLength(40)]
    [LocalizedDisplayNameAttribute]
    public string FirstName { get; set; }

    [Required]
    [StringLength(40)]
    [LocalizedDisplayNameAttribute]
    public string LastName { get; set; }
}

现在的问题是如何让这个课程:

public class LocalizedDisplayNameAttribute : DisplayNameAttribute
{
    private PropertyInfo _nameProperty;
    private Type _resourceType;

    public LocalizedDisplayNameAttribute(string className, string propertyName)
        : base(className + (propertyName == null ? "_Class" : ("_" + propertyName)))
    {

    }

    public override string DisplayName
    {
        get
        {
            return LanguageService.Instance.Translate(base.DisplayName) ?? "**" + base.DisplayName + "**";
        }
    }
}

了解我的属性名称,而不必在构造函数中指定它。

2 个答案:

答案 0 :(得分:2)

它适用于我。

[DataType(DataType.EmailAddress, ErrorMessageResourceName = "ThisFieldIsRequired", ErrorMessageResourceType = typeof(Resource))]
        [Required(ErrorMessageResourceName = "ThisFieldIsRequired", ErrorMessageResourceType = typeof(Resource))]
        [RegularExpression(@"^[\w-]+(\.[\w-]+)*@([a-z0-9-]+(\.[a-z0-9-]+)*?\.[a-z]{2,6}|(\d{1,3}\.){3}\d{1,3})(:\d{4})?$", ErrorMessageResourceName = "ThisFieldIsRequired", ErrorMessageResourceType = typeof(Resource))]
        [Display(Name = "EmailID", ResourceType = typeof(Resource))]
        public string EmailID { get; set; }

答案 1 :(得分:0)

我不确定这是否适用于您的情况,但我正在使用Model Meta数据扩展来本地化我的模型。它使模型更清洁。你试过这些吗?

http://haacked.com/archive/2011/07/14/model-metadata-and-validation-localization-using-conventions.aspx