The HtmlHelper
methods for generating a <select>
element (@Html.DropDownListFor()
etc) expect an IEnumerable<SelectListItem>
as one of the parameters, therefore your lstCustomers
should also be IEnumerable<SelectListItem>
public IEnumerable<SelectListItem> lstCustomers { get; set; }
You first line of code
var customersList = _context.Customers.Select(c => new SelectListItem { Value = c.LastName, Text = c.FullName });
is already generating that, so all that is required is
MyViewModel.lstCustomers = customersList;
You use of new SelectList(customersList , "Value", "Text");
is just creating another identical IEnumerable<SelectListItem>
from the first one and is unnecessary extra overhead. (SelectList
is IEnumerable<SelectListItem>
and is just a wrapper around it to provide constructors to generate the collection).
If you want to use SelectList
constructor then change your code to
var customersList = _context.Customers;
MyViewModel.lstCustomers = new SelectList(customersList , "LastName", "FullName");
Both will generate the same output. The difference between the methods is that the SelectList
constructor uses reflection to determine which properties to use for the options value and display text, so is fractionally slower, and it uses 'magic strings' so is not strongly typed. The benefit is that its a little less verbose.