我正在开发一个MVC 5应用程序.我想在我的控制器方法中的 [Display(Name ="")]属性中获取任何类的任何属性的值.
我的模型如下:
public partial class ABC
{
[Required]
[Display(Name = "Transaction No")]
public string S1 { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
我看过这个问题的答案,但这是一个有点冗长的程序.我正在寻找随时可用和内置的东西.
所以,我试过这个:
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>();
Run Code Online (Sandbox Code Playgroud)
但我有两个问题,首先我没有得到价值,即"交易否".其次,尽管我已经提到.OfType <>我仍然得到所有属性,即[Display(Name ="")]和[Required].
但幸运的是我获得了"交易否"的价值
property >> CustomAttribute >> [1] >> NamedArguments >> [0] >> TypedValue >> Value ="Transaction No"
由于TypedValue.Value具有所需的值,所以我该如何检索它?
Ale*_*rt. 20
这应该工作:
MemberInfo property = typeof(ABC).GetProperty(s);
var dd = property.GetCustomAttribute(typeof(DisplayAttribute)) as DisplayAttribute;
if(dd != null)
{
var name = dd.Name;
}
Run Code Online (Sandbox Code Playgroud)
你可以使用它:
MemberInfo property = typeof(ABC).GetProperty(s);
var name = property.GetCustomAttribute<DisplayAttribute>()?.Name;
Run Code Online (Sandbox Code Playgroud)