[英]What is the equivalent of .NET Framework ModelMetadataProvider in .Net Core?
for get property DisplayName
attribute value, ModelMetadataProvider
used at .NET Framework versions.对于获取属性
DisplayName
属性值, ModelMetadataProvider
用于 .NET 框架版本。
ModelMetadataProviders.Current.GetMetadataForProperty(null, ClassType, PropertyName).DisplayName;
and I tried get DisplayName
in .NET 6:我尝试在 .NET 6 中获取
DisplayName
:
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!将收到
DisplayName
值,但更改 CultureInfo 时 output 值不会更改!
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.使用下面的代码,可以在不使用ModelMetadataProvider和依赖注入的情况下访问DisplayName值(具有资源),并且它也可以通过更改语言来工作。
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();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.