Access displayName attribute from the model in MVC View

前端 未结 8 722
不思量自难忘°
不思量自难忘° 2021-02-06 22:51

If my model have

[DisplayName(\"First Name\")]
public string firstName { get; set; }

Then I can print it in the View with LabelFor



        
8条回答
  •  遇见更好的自我
    2021-02-06 23:12

    You can access the value of the attribute Display(Name="...") in 4 steps:

    var type = typeof(YourNamespace.Models.YourModelName);
    var memInfo = type.GetMember("firstName"); // your member
    var attributes = memInfo[0].GetCustomAttributes(typeof(System.ComponentModel.DataAnnotations.DisplayAttribute), false);
    var displayname = ((System.ComponentModel.DataAnnotations.DisplayAttribute)attributes[0]).Name;
    

    Then displayname will have the value First Name in your context.

提交回复
热议问题