O'Reilly logo

Professional ASP.NET MVC 3 by K. Scott Allen, Brad Wilson, Phil Haack, Jon Galloway

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Display and Edit Annotations

A long time ago, in a paragraph far, far away (at the beginning of this chapter, actually), you were building a form for a customer to submit the information needed to process an order. You did this using the EditorForModel HTML helper, and the form wasn't turning out quite how you expected. Figure 6.8 should help to refresh your memory.

Two problems are evident in the screenshot:

  • You do not want the Username field to display (it's populated and managed by code in the controller action)
  • The FirstName field should appear with a space between the words First and Name.

The path to resolving these problems also lies in the DataAnnotations namespace.

Like the validation attributes you looked at previously, a model metadata provider picks up the following display (and edit) annotations and makes their information available to HTML helpers and other components in the MVC run time. The HTML helpers use any available metadata to change the characteristics of a display and edit UI for a model.

Display

The Display attribute sets the friendly “display name” for a model property. You can use the Display attribute to fix the label for the FirstName field:

[Required]        
[StringLength(160, MinimumLength=3)]
[Display(Name="First Name")]
public string FirstName { get; set; }

With the attribute in place your view renders as shown in Figure 6.9.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required