Brian Brian - 6 months ago 77
ASP.NET (C#) Question

HTML.DropDownListFor DropDownList

I'm trying to retrieve data from my Database to an HTML instead of retrieving to the Html.DropDownListFor but I'm unable to retrieve to tag.


public class NewCustomerViewModel
public int CustId { get; set; }

public string CustFirstName { get; set; }

public string CustLastName { get; set; }

public int StId { get; set; }
public IEnumerable<State> States { get; set; }


public class CustomerController : Controller
private CustomerDbContext _context;

public CustomerController(CustomerDbContext context)
_context = context;

// GET: /<controller>/
public IActionResult Index()
return View(_context.Customers.ToList());

public IActionResult Create()
var stateNames = _context.States.ToList();
var viewModel = new NewCustomerViewModel
States = stateNames

return View(viewModel);

public IActionResult Create(Customer customer)
if (ModelState.IsValid)
return RedirectToAction("Index");

return View(customer);

Create View

The HTML DropDownListFor below works fine:

@Html.DropDownListFor(m => m.StId, new SelectList(Model.States, "StId", "StName"))

I'm unable to get the select tag to work though.

<select asp-for="StId" asp-items="@Model.States" class="form-control">
<option>Select State</option>

All of my HTML in my Create view using and rather than the HTML Helpers which is what I'm trying to avoid. I would just like to be able to retrieve the data to the tag instead.


For the select tag helper, asp-items expects SelectListItem collection\SelectList, and each item in that has a Value and Text property. The Value properties value will be used for the option's value and Text propertiesvalue will be used for the display text of the option in the UI.

Items in your States collection does not have a Value and Text property, but has StId and StName property. So we need to convert this type to SelectListItem type.

So your code should be

<select asp-for="StId"  asp-items="@(new SelectList(Model.States,"StId","StName"))">
     <option>Please select one</option>

Additional reference

Select Tag Helper in MVC 6