从MVC模型读取显示属性

问题描述 投票:0回答:1

在mvc中,我们如何从控制器中的模型中读取[display]属性

  public class RFModelIntro
{
    [Display(Name = "Your Email*")]
    [Required]
    public string Email { get; set; }
}

如果这是一个模型,我如何读取显示属性

我尝试过此代码,但没有成功

     //convert to key val pair first
      var model_keys = TypeDescriptor.GetProperties(typeof(RFModelIntro))
                          .Cast<PropertyDescriptor>()
                          .ToDictionary(p => p.Name, p => p.DisplayName);
        string model_val = "";  
   model_keys.TryGetValue("Email", out model_val);

model_val仍返回“电子邮件”

c# asp.net-mvc
1个回答
0
投票

尝试一下:

ModelMetadata.FromLambdaExpression<RFModelIntro, string>(x => x.Name, ViewData).DisplayName;

0
投票

您可以通过访问DisplayAttribute来阅读它

https://docs.microsoft.com/de-de/dotnet/api/system.componentmodel.dataannotations.displayattribute?view=netcore-3.1=

Object[] attr = yourInstance
  .GetType()
  .GetCustomAttributes(typeof(DisplayAttribute), true);

...

var display = attr[0].Name;

© www.soinside.com 2019 - 2024. All rights reserved.