Access displayName attribute from the model in MVC

2019-03-17 16:07发布

If my model have

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

Then I can print it in the View with LabelFor

@Html.LabelFor(model => model.acc_first)

It will then render as

<label for="firstName">First Name</label>
  • But how can I "raw" read the property (FirstName) attributes in the View? If for example, I want to send the value to a function on the View page

7条回答
再贱就再见
2楼-- · 2019-03-17 16:54

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);
}
查看更多
登录 后发表回答