What is the equivalent of .NET Framework ModelMetadataProvider in .Net Core?

Viewed 45

for get property DisplayName attribute value, ModelMetadataProvider used at .NET Framework versions.

ModelMetadataProviders.Current.GetMetadataForProperty(null, ClassType, PropertyName).DisplayName;

and I tried get DisplayName in .NET 6:

class SampleClass{
   [Display(Name = "FirstName", ResourceType = typeof(MyResource))]
   public string Name{ get; set; }
}

Type ClassType = typeof(SampleClass);
string PropertyName = "Name";
string displayName = TypeDescriptor.GetProperties(ClassType)
                            .Cast<PropertyDescriptor>()
                            .ToDictionary(p => p.Name, p => p.DisplayName)
                            .FirstOrDefault(p => p.Key == PropertyName).ToString(); 

The DisplayName value will be received, but the output value does not change when the CultureInfo is changed!

1 Answers

using the following code, DisplayName value (which has a resource) can be accessed without using ModelMetadataProvider and dependency injection, and it also works by changing the language.

class SampleClass{
   [Display(Name = "FirstName", ResourceType = typeof(MyResource))]
   public string Name{ get; set; }
}

Type ClassType = typeof(SampleClass);
string PropertyName = "Name";
string displayName = "";

MemberInfo property = ModelType.GetProperty(Property);
displayName = property.GetCustomAttribute<DisplayAttribute>()?.GetName();
            
Related