Fix: ASP.NET Core <select> control is empty

by

I found a nifty little quirk in ASP.NET Core recently where the <select> control (dropdown, combobox, listbox) is empty.  Basically, put a <select> control in your ASP.NET cshtml view, bind that control to a Model class with data, and then what shows up in the browser is an empty control.

It turns out that it’s just a minor difference in how the control is written in the HTML/XML of the view.  It’s the difference between using “<select></select>” and “<select />”.  Syntactically, that’s the same but ASP.NET Core handles it differently.

Here’s how it looks in the browser.

And if you open the dropdown menu, here’s what you get.

The select control is broken
The select control works

Here’s how that looks in the view (cshtml):

<!-- THIS VERSION IS BROKEN -->
<select asp-for="StateId2"
 asp-items="Model.States"
 class="form-control" />
 
<!-- THIS VERSION WORKS -->
<select asp-for="StateId1"
 asp-items="Model.States"
 class="form-control"></select>
 </div>

So if you run into this problem, just change your self-closing select tag to use a separate closing tag.

I hope this helps.

-Ben


Leave a Reply