4

I've seen many similar questions, but none seem to have a direct answer. When I attempt to add a Display(Name) attribute to a foreign key field, the Display Name isn't shown on the Create, Edit, Delete and Details form. I tried putting the attribute on the navigation property as well:

[Display(Name="Gender")]
public virtual Gender Gender {get; set;}

but that didn't work either.

public class Person
{
    public int ID {get; set;}
    public string FirstName {get; set;}
    public string LastName {get; set;}
    [Display(Name="Gender")]
    public int GenderID {get; set;}

    public virtual Gender Gender {get; set;}
}


public class Gender
{
    public int ID {get; set;}
    public string GenderName {get; set;}

    public virtual ICollection<Person> People {get; set;}       
}

2 Answers2

8

The solution is simple. After you add the display attribute in the model, remove the label name from the view.

So Change

            @Html.LabelFor(model => model.GenderID, "GenderID", htmlAttributes: new { @class = "control-label col-md-2" })

to

            @Html.LabelFor(model => model.GenderID, htmlAttributes: new { @class = "control-label col-md-2" })

in your view. This problem occurs when you scaffold your view.

aditya
  • 575
  • 7
  • 19
  • Seems weird that the scaffolding hard codes the label text into the LabelFor call, considering that the helper method is designed to dynamically pull that text, but you're right @aditya. – Paul Angelno Mar 22 '17 at 18:08
  • thanks @PaulAngelno Please mark it as answer if it helps! – aditya May 25 '17 at 00:29
  • It wasn't my question so I can't mark it as the answer but I already upvoted it. – Paul Angelno May 25 '17 at 14:45
1

It won't work on the navigation property, since that's never edited directly. You're either using the foreign key property or the individual properties on the related entity, not the entity itself.

However, that should have worked placed on the foreign key property, assuming you're actually using that property, and not the navigation property in your view, i.e.:

@Html.EditorFor(m => m.GenderID)
Chris Pratt
  • 232,153
  • 36
  • 385
  • 444
  • Hi Chris, thanks for your response. When I put the attribute on the foreign key property itself, it still doesn't show the display name. The drop down list is shown as expected. – Randell Lamont Feb 24 '15 at 19:44