Access displayName attribute from the model in MVC View
Asked Answered
E

9

38

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
Erubescent answered 14/9, 2011 at 15:10 Comment(1)
You should accept one of the answers below.Michiko
Z
59
@Html.DisplayNameFor(x => x.acc_first)
Zoezoeller answered 13/12, 2012 at 3:14 Comment(0)
P
13

To access the attributes you'll need a custom Html helper. Since the attributes aren't really part of the property or model you need to go in a round about way to access them.

public static IHtmlString DisplayName<TModel, TValue>(
                             this HtmlHelper<TModel> html,
                             Expression<Func<TModel, TValue>> expression) {
    var metadata = ModelMetadata.FromLambdaExpression<TModel, TValue>(expression, html.ViewData);

    return new HtmlString(metadata.DisplayName);
}

For additional attributes that aren't part of the DataAnnotations you can do the following:

Create a custom attribute

public class TooltipAttribute : Attribute, IMetadataAware {
    public TooltipAttribute(string tooltip) {
        this.Tooltip = tooltip;
    }

    public string Tooltip { get; set; }

    public void OnMetadataCreated(ModelMetadata metadata) {
        metadata.AdditionalValues["Tooltip"] = this.Tooltip;
    }
}

The magic happens in the OnMetadataCreated implementation. Here we can populate the AdditionalValues with anything we need for our particular Attribute. In this case we’re adding a Tooltip key. Your name should be unique as other attributes or providers may add their own keys with the same name It is important to remember that attributes are not always read in the same order. So your tooltip attribute may be called first, last or somewhere in the middle. This is an important distinction as it may cause undesired effects.

Then create a custom Attribute helper

public static IHtmlString TooltipFor<TModel, TValue>(
                             this HtmlHelper<TModel> html,
                             Expression<Func<TModel, TValue>> expression) {
    var metadata = ModelMetadata.FromLambdaExpression<TModel, TValue>(expression, html.ViewData);
    if (metadata.AdditionalValues.ContainsKey("Tooltip"))
        return new HtmlString((string)metadata.AdditionalValues["Tooltip"]);

    return new HtmlString("");
}
Pergola answered 14/9, 2011 at 15:49 Comment(1)
I am trying to use your example as @Html.TooltipFor(model=>model.Name) and keep getting error: The type argument for method cannot be inferred from usage, try specifying the arguments.Concourse
I
6

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.

Inoculum answered 27/11, 2015 at 13:22 Comment(0)
S
5

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);
}
Suzisuzie answered 25/7, 2017 at 1:51 Comment(0)
O
2

you should simply use

[Display(Name = "First Name")]


 public string name{ get; set; }
Ochlophobia answered 25/1, 2017 at 12:24 Comment(0)
B
0
<label asp-for="firstName">First Name</label>

you must change for to asp-for

Baywood answered 20/5, 2019 at 15:56 Comment(0)
D
0

[Display(Name ="First Name")]

Dielle answered 30/4, 2021 at 15:30 Comment(1)
This answer was already given right?Cortese
E
-3
@Html.DisplayFor(model => model.acc_first)

should work for you. If not, try just

@Model.acc_first

Either one should work fine.

Euripus answered 14/9, 2011 at 17:18 Comment(1)
The question is asking about getting the property's Display Name (from the DisplayNameAttribute), not the property's value.Zoezoeller
S
-4

@(This.Model.acc_first)

Should work

so in javascript you can use it like

function callme(val)
{
   //some ajax call with 
   @(This.Model.acc_first)
}
Smelt answered 14/9, 2011 at 15:19 Comment(1)
The question is asking about getting the property's Display Name (from the DisplayNameAttribute), not the property's value.Zoezoeller

© 2022 - 2024 — McMap. All rights reserved.