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))
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With