Dismissile
Dismissile

Reputation: 33071

Get DisplayAttribute of Parent Property

I have a View Model that is defined as follows:

public class VariableViewModel
{
    public string TemplateName { get; set; }
    public bool Enabled { get; set; }
    public string Value { get; set; }
}

I am using this model in other View models:

public class CreateViewModel
{
    [Display(Name="First Name")]
    public VariableViewModel FirstName { get; set; }

    [Display(Name="Last Name")]
    public VariableViewModel LastName { get; set; }
}

I have an editor template defined for VariableViewModel:

@model VariableViewModel

@Html.HiddenFor(model => model.TemplateName)
@Html.HiddenFor(model => model.Enabled)
@Html.LabelFor(model => model.Value)
@Html.TextBoxFor(model => model.Value)

An editor template for my CreateViewModel:

@model CreateViewModel

@Html.EditorFor(model => model.FirstName)
@Html.EditorFor(model => model.LastName)

Right now my editor template is creating the label as follows:

<label for="FirstName">Value</label>

Is it possible to modify LabelFor in a way that it looks at the DisplayAttribute of the parent property to determine what it should use instead of having it be Value? I want my labels to look like:

<label for="FirstName">First Name</label>
<label for="LastName">Last Name</label>

The problem is that the Display attribute is not on the property I am creating the label for, but on the containing object. Is there a way to accomplish what I want?

Upvotes: 1

Views: 355

Answers (1)

Darin Dimitrov
Darin Dimitrov

Reputation: 1038710

In your editor template simply use the following for the label:

@Html.LabelFor(model => model.Value, ViewData.ModelMetadata.DisplayName)

We are passing the parent display name as value for the label.

Upvotes: 5

Related Questions