How do you populate a dropdown list in ASP.NET MVC?

ASP.NET MVC Views & Razor Basic Fresher1–2 Yrs Coding 1 min read

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 Categories from the service.
  • Controller POST on !ModelState.IsValid: fill Categories again, then return View(vm) — otherwise the dropdown renders empty.
  • Prefer the view model over ViewBag for the list — it's typed and self-documenting.