Strongly-typed binding to a DropDownListFor?
asp.net, asp.net-mvc, asp.net-mvc-5, c#, html.dropdownlistfor
Solution
You could create the select list itself in the controller and assign it to a property in your view model:
public IEnumerable<SelectListItem> OrdersList { get; set; }
The code in your controller will look like this:
model.OrdersList = db.Orders
.Select(o => new SelectListItem { Value = o.OrderId, Text = o.ItemName })
.ToList();
In the view you can use it like this:
@Html.DropDownListFor(model => model.CustomerId, Model.OrderList)
I personally prefer this approach since it reduces logic in your views. It also keeps your logic 'stronly-typed', no magic strings anywhere.
Problem
Normally I would bind data to a `DropDownListFor` with a `SelectList`: ``` @Html.DropDownListFor(model => model.CustomerId, new SelectList(Model.Orders, "OrderId", "ItemName")) ``` Is there any way to do this through strongly-typed lambdas and not with property strings. For example: ``` @Html.DropDownListFor(model => model.CustomerId, new SelectList(Model.Orders, x => x.OrderId, x => x.ItemName)) ```