Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

asp.net-mvc

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 =/

like image 750
Niklas Avatar asked May 24 '11 12:05

Niklas


3 Answers

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; }
like image 181
Daniel A. White Avatar answered Nov 15 '22 04:11

Daniel A. White


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; }
}
like image 37
Niklas Avatar answered Nov 15 '22 03:11

Niklas


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; }
like image 33
Tor-Erik Avatar answered Nov 15 '22 04:11

Tor-Erik