0

I am able to localize model classes properties in a following way:

public class Person
{
     [Display(Name = ResourceKeys.Person_FirstName)]
     [Required(Name = ResourceKeys.Person_FirstName_Required)]
     public string FirstName { get; set; }

     //...other properties
}

Where "ResourceKeys" is special class, that stores the "pseoudo" keys and links them with the "proper" keys in relevant resource file:

public class ResourceKeys
{
     public const string Person_FirstName = "FirstName"; // looks up for key "FirstName" in Person."culture".resx file
     public const string Person_FirstName_Required = "FirstName_Required"; //dtto
     //...
}

This works well - for example @Html.DisplayNameFor(model => model.FirstName) is localized correctly and rendered as 'Vorname' for german language.

Now to the problem. When new class is derived, the derived properties are not localized:

public class Student : Person
{
     //...
}

For example @Html.DisplayNameFor(model => model.FirstName) is probably not localized at all and rendered as 'FirstName'. It seems like only the student resource file is searched for the key and as it is not found the key itself is rendered.

I definitely want to avoid duplicates in resource files of base and derived classes. How can I achieve this?


Edit: Localization of derived properties does not work even if the ResourceKeys class is omitted and annotation strings are directly "hardcoded":

public class Person
{
     [Display(Name = "FirstName")]
     [Required(Name = "FirstName_Required")]
     public string FirstName { get; set; }

     //...other properties
}
Pavel
  • 11
  • 3
  • I think you may need to set the resource type to ensure the lookup occurs in the correct resource file: `[Display(ResourceType = typeof(Person), Name = ResourceKeys.Person_FirstName)]` – Lennart Stoop Jun 05 '19 at 10:52
  • After this i get following error: `InvalidOperationException: Cannot retrieve property 'Name' because localization failed. Type 'Person' is not public or does not contain a public static string property with the name 'FirstName'.` Class is public and I cannot make the property static. Should I add static property called like FirstName_Name and refer to it in display name? – Pavel Jun 05 '19 at 11:13
  • No, the resource type `typeof(Person)` should refer to the class that is generated for the resx file. You need to make sure it is public and does not conflict with your actual `Person` class (you may need to specify a namespace if the class names are the same), see also: https://stackoverflow.com/questions/4274311/visual-studio-resx-file-default-internal-to-public – Lennart Stoop Jun 05 '19 at 11:25
  • Thank you! Although I must admit I hoped for something more elegant. – Pavel Jun 05 '19 at 12:42
  • Yup I agree, an alternative approach would be to [create your own attribute and implement a custom lookup](https://stackoverflow.com/a/357008/1145403) – Lennart Stoop Jun 05 '19 at 13:00

0 Answers0