MVC3 Localized display name attribute by property name

I recently learned how to create localized display names for my model properties using the following article: Simplified Localization for DataAnnotations

And now I'm trying to push it a little further by removing the parameters from the constructor. Value instead

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 it

 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 to resolve 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 name without specifying it in the constructor.

+4
source share
2 answers

This works great 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-]+)*?\.[az]{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
source

I'm not sure if this is relevant to your case, but I am using Model metadata extensions to localize my models. He keeps the model cleaner. Have you tried this?

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

0
source

Source: https://habr.com/ru/post/1482357/


All Articles