Access displayName attribute from the model in MVC View

前端 未结 8 723
不思量自难忘°
不思量自难忘° 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:11
    @Html.DisplayFor(model => model.acc_first)
    

    should work for you. If not, try just

    @Model.acc_first
    

    Either one should work fine.

    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2021-02-06 23:22
    <label asp-for="firstName">First Name</label>
    

    you must change for to asp-for

    0 讨论(0)
  • 2021-02-06 23:23

    you should simply use

    [Display(Name = "First Name")]
    
    
     public string name{ get; set; }
    
    0 讨论(0)
  • 2021-02-06 23:24

    Building on Darren Oster's answer:

    @Html.DisplayNameFor(x => x.acc_first)
    

    Here's a link to the documentation for this: https://msdn.microsoft.com/en-us/library/system.web.mvc.html.displaynameextensions.displaynamefor(v=vs.118).aspx

    You could use this in your view code like this:

    @{ 
        var foo = Html.DisplayNameFor(x => x.acc_first);
    
        // call function
        DoStuff(foo);
    }
    
    0 讨论(0)
  • 2021-02-06 23:31
    @Html.DisplayNameFor(x => x.acc_first)
    
    0 讨论(0)
提交回复
热议问题