加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – 如何使用EF6获取Controller中[Display(Name =“”)]属性中

发布时间:2020-12-15 08:08:34 所属栏目:百科 来源:网络整理
导读:我正在开发一个MVC 5应用程序.我想在我的控制器方法中的[Display(Name =“”)]属性中获取任何类的任何属性的值. 我的模型如下: public partial class ABC{ [Required] [Display(Name = "Transaction No")] public string S1 { get; set; }} 我看了answer to
我正在开发一个MVC 5应用程序.我想在我的控制器方法中的[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>();

但我有两个问题,首先我没有得到价值,即“交易否”.其次,尽管我已经提到过.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;
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读