Shay Friedman
Shay Friedman

Reputation: 4868

Using Html.LabelFor to display human readable label?

I'm using ASP.NET MVC 2 and I'm struggling to understand how can I use the Html.LabelFor helpet method.

Assuming I have a model:

public class Person
{
  public string FirstName { get; set; }
}

In my view, if I write:

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

What I get on the page is "FirstName". But I don't want that because it's not user-friendly. I want it to be "First Name".

How do I achieve that?

Thanks.

Upvotes: 7

Views: 10089

Answers (3)

jamiebarrow
jamiebarrow

Reputation: 2517

Nathan Taylor's answer is the easiest. Another answer would be to create a custom DataAnnotationsModelMetadataProvider, which gets the property name and splits it using some string helper. Manning's ASP.NET MVC2 in Action (2nd Edition) has an example of this in Chapter 15.

Upvotes: 0

Rob
Rob

Reputation: 6871

This should work

<%= Html.LabelFor(model => model.FirstName) %>

Upvotes: -1

Nathan Taylor
Nathan Taylor

Reputation: 24606

Just like this:

public class Person
{
  [DisplayName("First Name")]
  public string FirstName { get; set; }
}

System.ComponentModel.DisplayNameAttribute

You should also check out System.ComponentModel.DataAnnotations for some incredibly helpful validation attributes like [Range(0, 100)], [StringLength(100)], [Required] and more.

Upvotes: 24

Related Questions