Menü Schließen

Using Enums in ASP.NET MVC

If you use enumerations, you usually prefer not to see the internal value of the enum in the GUI, but a human readable (maybe localized) string.

The following example shows how easy it is to accomplish that in ASP.NET MVC.

We use the following example class that represents a change in a software:

public class Change
  public Change()
    ID = Guid.NewGuid();

  public Guid ID { get; set; }

  [Required(ErrorMessage = "Der Typ ist erforderlich.")]
  [Display(Name = "Typ")]
  public ChangeType ChangeType { get; set; } = ChangeType.Bug;

  [Required(ErrorMessage = "Die Beschreibung ist erforderlich.")]
  [Display(Name = "Beschreibung")]
  public string Description { get; set; }

  public ApplicationVersion Version { get; set; }

  public Guid Version_ID { get; set; }

The important part for this post is the ChangeType property. It is of Type ChangeType, which is an enumeration. We’re using data annotations to change the display value of the type into a localized version and to define constraints.

The ChangeType enumeration looks like this:

public enum ChangeType
  [Display(Name = "Fehler")]
  [Display(Name = "Feature")]
  [Display(Name = "Verbesserung")]
  [Display(Name = "Info")]

As you can see, the ChangeType values are also annotated with localized strings defining the display name.

This already works automatically for DropDown lists when using the following Razor syntax:

@Html.EnumDropDownListFor(model => model.ChangeType, htmlAttributes: new { @class = "form-control" })

However it will not work automatically when we try to display the enum by using the DisplayFor HtmlHelper extension:

@Html.DisplayFor(model => model.ChangeType)

To enable this feature also there, you’ll have to create a custom DisplayTemplate. Create folder Views\Shared\DisplayTemplates in your project. There you add a new partial view named Enum.

Here’s the content of the new class:

@model Enum

@if (EnumHelper.IsValidForEnumHelper(ViewData.ModelMetadata))
  // Display Enum using same names (from [Display] attributes) as in editors
  string displayName = null;
  foreach (SelectListItem item in EnumHelper.GetSelectList(ViewData.ModelMetadata, (Enum)Model))
    if (item.Selected)
      displayName = item.Text ?? item.Value;

  // Handle the unexpected case that nothing is selected
  if (String.IsNullOrEmpty(displayName))
    if (Model == null)
      displayName = String.Empty;
      displayName = Model.ToString();

  @Html.DisplayTextFor(model => displayName)
  // This Enum type is not supported. Fall back to the text.
  @Html.DisplayTextFor(model => model)


Ähnliche Beiträge

Schreibe einen Kommentar

Deine E-Mail-Adresse wird nicht veröffentlicht. Erforderliche Felder sind mit * markiert