如何使用EF6在Controller中为任何属性获取[Display(Name =“"“))]属性中的值 [英] How to get the Value in [Display(Name="")] attribute in Controller for any property using EF6

查看:322
本文介绍了如何使用EF6在Controller中为任何属性获取[Display(Name =“"“))]属性中的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发MVC 5应用程序.我想在控制器方法的任何类的任何属性的 [Display(Name ="))] 属性中获取值.

I am developing an MVC 5 application. I want to get the value in [Display(Name = "")] attribute in my controller method for any property of any class.

我的模特是:

public partial class ABC
{
   [Required]
   [Display(Name = "Transaction No")]
   public string S1 { get; set; }
}

我已经看过此问题的答案,但这有点冗长的过程.我正在寻找随时可用且内置的东西.

I have looked answer to this question, but it is a little lengthy procedure. I am looking for something readily available and built-in.

所以,我已经尝试过了:

So, I have tried this:

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].

But I have 2 problems, First I am not getting the value i.e. "Transaction No". And secondly even though I have mentioned .OfType<> I am still getting all attributes i.e. [Display(Name="")] and [Required].

但幸运的是,我在

属性>>自定义属性>> [1] >>命名参数>> [0] >>类型值>>值 =交易编号"

property>>CustomAttribute>>[1]>>NamedArguments>>[0]>>TypedValue>>Value = "Transaction No"

由于 TypedValue.Value 具有必需的值,所以如何检索它?

Since TypedValue.Value has the required value, So how can I retrieve it?

推荐答案

这应该有效:

MemberInfo property = typeof(ABC).GetProperty(s); 
var dd = property.GetCustomAttribute(typeof(DisplayAttribute)) as DisplayAttribute;
if(dd != null)
{
  var name = dd.Name;
}

这篇关于如何使用EF6在Controller中为任何属性获取[Display(Name =“"“))]属性中的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆