4

我最近学习了如何使用以下文章为我的模型属性创建本地化显示名称: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 + "**";
        }
    }
}

无需在构造函数中指定即可知道我的属性的名称。

4

2 回答 2

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; }
于 2014-05-14T14:10:13.163 回答
0

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

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

于 2013-10-31T16:52:49.813 回答