c# - 如何使用 EF6 获取 Controller 中任何属性的 [Display(Name ="")] 属性中的值

标签 c# asp.net-mvc

我正在开发 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/

相关文章:

c# - 组合时间范围

c# - 如何动态获取文本框中datagridview列的总和

c# - 是否可以在针对 4.7.1 的 WinForms 项目中使用 Path.GetRelativePath (.NET Core2)?

jquery - getJSON 回调未触发

asp.net-mvc - Fluent NHibernate 和存储库模式

c# - 使用事件处理程序尝试 Catch

c# - 重新抛出异常困难——异常使程序崩溃而不是重新抛出

asp.net-mvc - Razor:无法在 @Section 中渲染 Html.Label 帮助程序(仅输出源)

jquery - 使用 JQuery 将表单序列化为嵌套 JSON

asp.net-mvc - 如何将文件内容添加到Viewbag mvc4