Html.LabelFor and DisplayNameAttribute in ASP.NET MVC 2.0 - Tutorials and Examples

Continuing my series of ASP.NET MVC 2.0 Tutorials that are subject to change when ASP.NET MVC 2.0 gets released as a part of Visual Studio 2010:

Although the names may change, I think the concepts will remain the same.

 

DisplayNameAttribute in System.ComponentModel.DataAnnotations

The template helpers in ASP.NET MVC 2.0 ( Html.DisplayFor, Html.EditorFor, and Html.LabelFor ) work in coordination with a lot of the attributes in System.ComponentModel.DataAnnotations. Another attribute that could be useful, especially for legacy databases and/or O/R Mappers like LINQ To SQL and Entity Framework that read schema directly from the database, is the DisplayNameAttribute.

Normally, if you use the Html.LabelFor Template Helper in ASP.NET MVC 2.0 it will use the name of the property as the label in your views. If we look at the Contact Manager code we have been working with to date, whenever we use the following template helper:

 

Html.LabelFor(c = > c.Name )

 

Name“ would be displayed as the label for that property in your ASP.NET MVC Views. If we look at the default Details View for Contacts that uses Html.LabelFor(c => c.Name ) we see the “Name” Label for the name of the contact:

 

Html.LabelFor in ASP.NET MVC 2.0

 

This is pretty intuitive and what you would expect as a default label. However, you can change the label by adding a DisplayNameAttribute to the Name Property. Let's pretend we want the label to say “Contact Name“ instead of the default Name. If we go to the Contact Class and add the following DisplayNameAttribute:

 

[DisplayName("Contact Name")]

public string Name { get; set; }

 

The default details view ( which uses Html.LabelFor(c => c.Name ) ) now has the label “Contact Name“ for the Name Property:

 

Html.LabelFor in ASP.NET MVC 2.0

 

As mentioned before, the DisplayNameAttribute becomes especially handy when 1) you are not in control of the property names, 2) the property names are code generated by a visual designer like those with LINQ To SQL and Entity Framework, or 3) you just want the label to be different than the name of the property. For code generated classes, you can create a Metadata Buddy Class and add the DisplayNameAttribute to its properties so as not to disturb the code generated classes.

 

Hope this helps,

David Hayden

 

ASP.NET MVC Book Reviews

 

posted on Wednesday, August 19, 2009 11:03 AM

Main

News

Green Tea

.NET Development

Enterprise Library

Patterns & Practices