Reputation: 144
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.
Upvotes: 4
Views: 3947
Reputation: 37642
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; }
Upvotes: 2
Reputation: 2187
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?
Upvotes: 0