MVC3 Localized display name attribute by property name

余生颓废 提交于 2019-12-22 08:40:16

问题


I have recently learned how to create a localized display names for my model's properties using the following article: Simplified localization for DataAnnotations

And I am now trying to push it a bit further by removing the parameters from the constructor. Meaning instead of having this

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

I want to have this

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

Now the question is how do I let this class:

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 + "**";
        }
    }
}

Know my property's name without having to specify it in the constructor.


回答1:


It works fine for me.

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



回答2:


I'm not sure if this applies to your case, but I'm using Model Meta data extensions for localizing my models. It keeps the model cleaner. Have you tried these?

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



来源:https://stackoverflow.com/questions/16711579/mvc3-localized-display-name-attribute-by-property-name

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