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.