Strongly typed DropDownListFor binding?

I usually bind data to DropDownListForwith SelectList:

@Html.DropDownListFor(model => model.CustomerId, new SelectList(Model.Orders, "OrderId", "ItemName"))

Is there a way to do this with 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))
+4
source share
3 answers

You can create the selection list itself in the controller and assign it to a property in your viewing 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 a view, you can use it as follows:

@Html.DropDownListFor(model => model.CustomerId, Model.OrderList)

, . "", .

+10

. DataTextField DataValueField ?

0

u ViewBag Drop Down Control

..............

@Html.DropDownList("department", (IEnumerable<SelectListItem>)@ViewBag.DepartmentList, new { value = @ViewBag.department, style = "width:140px", onchange = "OnDepartmentChange(this)" })

,

 ViewBag.Department = department;
0

All Articles