繁体   English   中英

从 MVC model 读取显示属性

[英]Read the display attribute from MVC model

在 mvc 中,我们如何从 controller 中的 model 读取 [display] 属性

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

如果这是 model,我如何读取显示属性

我试过这段代码,但没有成功

     //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 仍在返回“电子邮件”

尝试这个:

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

您可以通过访问 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;

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM