Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Strongly-typed binding to a DropDownListFor?

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))
like image 937
Dave New Avatar asked Dec 06 '13 09:12

Dave New


1 Answers

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.

like image 74
Henk Mollema Avatar answered Sep 21 '22 15:09

Henk Mollema