gpt4 book ai didi

c# - MVC3 按属性名称本地化显示名称属性

转载 作者:行者123 更新时间:2023-11-30 12:30:14 25 4
gpt4 key购买 nike

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

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

最佳答案

它对我来说很好。

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

关于c# - MVC3 按属性名称本地化显示名称属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16711579/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com