繁体   English   中英

.Net Core中的.NET Framework ModelMetadataProvider相当于什么?

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

对于获取属性DisplayName属性值, ModelMetadataProvider用于 .NET 框架版本。

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

我尝试在 .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(); 

将收到DisplayName值,但更改 CultureInfo 时 output 值不会更改!

使用下面的代码,可以在不使用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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM