根据属性名MVC3本地化显示名称属性 [英] MVC3 Localized display name attribute by property name

查看:94
本文介绍了根据属性名MVC3本地化显示名称属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我最近学会了如何创建使用下面的文章我的模型的属性本地化的显示名称:的为DataAnnotations 简化本地化

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

我想有这种

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.

推荐答案

它工作正常的我。

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

这篇关于根据属性名MVC3本地化显示名称属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆