Niklas
Niklas

Reputation: 13135

Is it possible to specify a label for a field in the model?

I'd like to specify a "label" for a certain field in the model and use it every where in my application.

<div class="editor-field">
<%: Html.TextBoxFor(model => model.surname) %>
<%: Html.ValidationMessageFor(model => model.surname) %>
</div>  

To this I'd like to add something like:

<%: Html.LabelFor(model => model.surname) %>  

But labelFor already exist and writes out "surname". But I want to specify what it should display, like "Your surname".
I'm sure this is easy =/

Upvotes: 5

Views: 3152

Answers (3)

Tor-Erik
Tor-Erik

Reputation: 1000

Yes, you can do this by adding the DisplayAttribute (from the System.ComponentModel.DataAnnotations namespace) to the property: something like this:

[Display(Name = "Your surname")]
public string surname { get; set; }

Upvotes: 1

Niklas
Niklas

Reputation: 13135

Since my project was auto generated I couldn't (shouldn't) alter the designer.cs file.
So I created a meta data class instead, as explained here

// Override the designer file and set a display name for each attribute
[MetadataType(typeof(Person_Metadata))]
public partial class Person
{
}

public class Person_Metadata
{
    [DisplayName("Your surname")]
    public object surname { get; set; }
}

Upvotes: 1

Daniel A. White
Daniel A. White

Reputation: 190945

Use the Display or DisplayName attribute on the property in your model.

[Display(Name = "Your surname")]
public string surname { get; set; }

or

[DisplayName("Your surname")]
public string surname { get; set; }

Upvotes: 9

Related Questions