Search code examples
c#model-view-controllerasp.net-core-mvc

Troubleshooting Dropdown Display of Enum Values in ASP.NET Core MVC


I want to allow the user to download the report, when it is approved by a supervisor. At the moment, I'm working with manager account, where he can check many reports and change their state to either verified or denied, but I don't understand why the report states enum list is not displaying, even though it is shown in the console.

HTML code

Model:

public class Report
{
    public int ID { get; set; }
    [Display(Name = "Report Name")]
    public string reportName { get; set; }
    public virtual User reportManager { get; set; }
    [Display(Name = "State")]
    public ReportState reportState { get; set; }
    public byte[] reportData { get; set; }
}

public enum ReportState
{
    Accepted,
    Pending,
    Denied
}

Controller:

public async Task<IActionResult> Index()
    {
        ViewBag.Reports = await _context.Reports.ToListAsync();

        ViewBag.ReportStates = new SelectList(Enum.GetNames(typeof(ReportState)));

        return View();
    }

@model variable_pay_system.Models.Report

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

<div class="container">
<h5>Reports</h5>
<table>
    <thead>
        <tr>
            <th>
                @Html.DisplayNameFor(model => model.reportName)
            </th>
            <th>
                @Html.DisplayNameFor(model => model.reportState)
            </th>
        </tr>
    </thead>
    <tbody>
        @foreach (Report report in ViewBag.Reports)
        {
        <tr>
            <td>
                @Html.DisplayFor(modelItem => report.reportName)
            </td>
            <td>
                <select asp-for="@report.reportState" asp-items="Html.GetEnumSelectList<ReportState>()"></select>
            </td>
        </tr>
        }
    </tbody>
</table>

Solution

  • The problem was because, I was missing this code at the end.

    <script>
    $(document).ready(function () {
        $('select').formSelect();
    });
    </script>