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.

Get Professional ASP.NET MVC 3 now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.