DEV Community

catrina
catrina

Posted on • Originally published at catrina.me on

.Net Core – Drop Down (Select) Won’t Populate

I had a recent bug that took me much too long to solve and the root of the cause was me. I got a bit too delete happy and deleted a crucial file that allows me to use Razor Tag Helpers to bring a List into a View as a Drop Down (Select).

The Error

Here’s how the error presented itself:

  • SelectList won’t populate
  • Select or DropDown is empty
  • value = Microsoft.AspNetCore.Mvc.Rendering.SelectList
  • value = System.Linq.OrderedEnumerable2 [Microsoft.AspNetCore.Mvc.Rendering.SelectListItem,System.String]

My Code

This is how I usually bring a list into my view and the code does work once the solution is implemented.

Controller:

    ViewBag.ProductLines = productLineRepository.GetAll().Select(r => new SelectListItem {
         Text = r.Name, 
         Value = r.Id.ToString() 
    }).OrderBy(x => x.Text).ToList();
Enter fullscreen mode Exit fullscreen mode

View:

    <select name="ProductLine" id="ProductLine" asp-for="ProductLine" asp-items="@ViewBag.ProductLines">
    <option value="0">Select One...</option>
    </select>
Enter fullscreen mode Exit fullscreen mode

The Solution

The solution is a bit embarrasing: I deleted the _ViewImports.cshtml view which included an import that enables tag helpers. The list was not rendering because tag helpers was not enabled.

To solve this:

  • create a file named “_ViewImports.cshtml” directly under your Views folder
  • add the following into it:
@using MyNameSpace @addTagHelper \*, Microsoft.AspNetCore.Mvc.TagHelpers
Enter fullscreen mode Exit fullscreen mode
  • save file and refresh.

Pretty simple fix!

Top comments (0)