我正在开发 MVC 5 应用程序。我想在我的 Controller 方法中为任何类的任何属性获取 [Display(Name = "")] 属性中的值。
我的模型如下:
public partial class ABC
{
[Required]
[Display(Name = "Transaction No")]
public string S1 { get; set; }
}
我看过answer to this question , 但这是一个有点冗长的过程。我正在寻找现成的和内置的东西。
所以,我试过这个:
MemberInfo property = typeof(ABC).GetProperty(s); // s is a string type which has the property name ... in this case it is S1
var dd = property.CustomAttributes.Select(x => x.NamedArguments.Select(y => y.TypedValue.Value)).OfType<System.ComponentModel.DataAnnotations.DisplayAttribute>();
但我有 2 个问题,首先我没有得到值,即“交易号”。其次,即使我提到了 .OfType<>,我仍然获得所有属性,即 [Display(Name="")] 和 [Required]。
但幸运的是我在
中得到了“交易号”值property>>CustomAttribute>>[1]>>NamedArguments>>[0]>>TypedValue>>Value = "Transaction No"
由于 TypedValue.Value 具有所需的值,那么我该如何检索它呢?
最佳答案
这应该有效:
MemberInfo property = typeof(ABC).GetProperty(s);
var dd = property.GetCustomAttribute(typeof(DisplayAttribute)) as DisplayAttribute;
if(dd != null)
{
var name = dd.Name;
}
关于c# - 如何使用 EF6 获取 Controller 中任何属性的 [Display(Name ="")] 属性中的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32808132/