Home > OS >  How to display different name for properties in enum class in @Html.DropDownListFor
How to display different name for properties in enum class in @Html.DropDownListFor

Time:09-16

Lets say I have the model:

using System.ComponentModel.DataAnnotations;

namespace MyProject.Models
{
   public class InputParametersModel
   {        
      public Variable Xvariable { get; set; }

      public Variable Yvariable { get; set; }
   }

    public enum Variable
    {
        [Display(Name = "A A")]
        aa,
        [Display(Name = "B B")]
        bb,
        [Display(Name = "C C")]
        cc,
    }
}

and my view has:

@model MyProject.Models.InputParametersModel
@using MyProject.Models

<div>
@using (Html.BeginForm())
{
@Html.DropDownListFor(m => m.Xvariable, new SelectList(Enum.GetValues(typeof(Variable))), "Select", new { @class = "form-control"})
@Html.DropDownListFor(m => m.Yvariable, new SelectList(Enum.GetValues(typeof(Variable))), "Select", new { @class = "form-control"})
}
</div>

How do I get the dropdowns to display "A A", "B B" and "C C"? I thought adding [Display(Name = "A A")] would solve my problem but it's still displaying 'aa' etc.

(this just a snippet of the code but hopefully I accounted for any syntax errors)

Edit: forgot to copy @using (Html.BeginForm())

CodePudding user response:

You can show display names using Html.GetEnumSelectList in .Net Core

@Html.DropDownListFor(m => m.Xvariable,Html.GetEnumSelectList<Variable>(),
                                    new { @class = "form-control" })

//Or

<select asp-for="Xvariable" asp-items="Html.GetEnumSelectList<Variable>()">
     <option selected="selected" value="">Please select</option>
</select>
  • Related