How do you populate a dropdown list in ASP.NET MVC?
Quick Answer
Put a List<SelectListItem> (or an IEnumerable plus a SelectList) on your view model and bind the dropdown with <select asp-for="CategoryId" asp-items="Model.Categories"></select>. On a failed POST you must re-populate the list before re-rendering the view — it isn't posted back.
I put the list of options on the view model as IEnumerable<SelectListItem>, and the selected value as a separate property like CategoryId. In the view it's <select asp-for="CategoryId" asp-items="Model.Categories">. The mistake people make is on the POST — if validation fails and I re-render the view, the options list isn't part of the form data, so I have to reload it in the controller before returning the view, or the dropdown comes back empty.
- View model:
public int CategoryId { get; set; }+public IEnumerable<SelectListItem> Categories { get; set; }. - Controller GET: fill
Categoriesfrom the service. - Controller POST on
!ModelState.IsValid: fillCategoriesagain, thenreturn View(vm)— otherwise the dropdown renders empty. - Prefer the view model over
ViewBagfor the list — it's typed and self-documenting.