Search code examples
c#htmldropdown

Populating a dropdownlist with enum


I am trying to populate a dropdown list with enum values but I am running into issues. This is my class

public class Project
    {
        ...
        public Currencies Money { get; set; }

        public enum Currencies
        {
            [Display(Name = "Euro")]
            Euro = 1,
            [Display(Name = "USD")]
            USD = 2
        }

and this is my view

@model Projects.Domain.Project

@{
    ViewData["Title"] = "Create";
}

<br />
<p style="font-weight:bold;">Add new project</p>
<hr />
<div class="row">
    <div class="col-md-4">
        <form asp-action="Create">            
            <div class="form-group">
                <select asp-for="Money" asp-items="@Html.GetEnumSelectList<Currencies>()"></select>
            </div>
        </form>
    </div>
</div>

but I am getting an error saying The type or namespace currencies could not be found. It's the same if I substitute Currencies with Money. What is the correct way to populate the dropdown list?


Solution

  • You can try with Full name: Projects.Domain.Project.Currencies

    Select code:

     <select asp-for="Money" asp-items="@Html.GetEnumSelectList<Projects.Domain.Project.Currencies>()"></select>
    

    Or with Using namespace:

    @using Projects.Domain
    

    Select code:

     <select asp-for="Money" asp-items="@Html.GetEnumSelectList<Project.Currencies>()"></select>