0

I'm loading a ListBox from a model which looks like this

public class FilterModel
{
    public Learning TypeOfLearning { get; set; }
    public TeachingYear Teaching { get; set; }
}

public enum Learning
{
    All,
    Frameworks,
    Qualifications,
    Units,
    Standards
}

public enum TeachingYear
{
    2016/2017,
    2017/2018,
    2018/2019,
    2019/2020
}

The values are loaded into my ListBox as below

 @Html.DropDownList("LearningType", new SelectList(Enum.GetValues(typeof(Learning))),
                              "Select Learning Type", new { @style = "width: 350px" })

 @Html.DropDownList("TeachingYeare",
                              new SelectList(Enum.GetValues(typeof(TeachingYear))),
                              "Select Teaching Year", new { @style = "width: 350px" })

Learning works fine but TeachingYear objects to the numeric values which I've tried parsing but it still wont run. How do I set up my enum to correctly display the date range values?

Tetsuya Yamamoto
  • 24,297
  • 8
  • 39
  • 61
user616076
  • 3,907
  • 8
  • 38
  • 64

2 Answers2

0

As per MSDN documentation,

An enumeration is a set of named constants whose underlying type is any integral type

Being constants, their name can't be defined using numbers as their first character, just like any other variable. Also, considering that every teaching year will always finish the year after it started, putting the ending year in the name itself is redundant. I suggest you should change the name and use attribute decorators like this:

using System.ComponentModel.DataAnnotations;    

public enum TeachingYear
{
    [Display(Name = "2016/2017")]
    _2016,
    [Display(Name = "2017/2018")]
    _2017,
    [Display(Name = "2018/2019")]
    _2018,
    [Display(Name = "2019/2020")]
    _2019
}

so that, when using the EnumDropDownListFor html helper, descriptions are automatically shown in the list, while values are bound to the object. See also this answer here.

EDIT: Considering your latest comment about the framework, in the view

@Html.GetEnumSelectList<TeachingYear>()

should do it, but I’ve never used .NET Core so you’d better check the relative MSDN documentation for proper usage.

Davide Vitali
  • 1,017
  • 8
  • 24
0

In your View , you could try the following changes :

        <div class="form-group">
            <select asp-for="learning"
                    asp-items="@Html.GetEnumSelectList<Learning>()">
                <option>Select Learning Type</option>
            </select>
        </div>
        <div class="form-group">
            <select asp-for="learning"
                    asp-items="@Html.GetEnumSelectList<TeachingYear>()">
                <option>Select Teaching Year</option>
            </select>
        </div>
Xueli Chen
  • 11,987
  • 3
  • 25
  • 36