Strongly-typed binding to a DropDownListFor?

Viewed 5990

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))
4 Answers

There doesn't appear to be an overloaded constructor to allow for this. But there's no harm in manually specifying the DataTextField and DataValueField as a string is there?

for that u can use a ViewBag for storing a data into your Drop Down Control

here is an example of it ..............

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

in controller in Index method you can write like

 ViewBag.Department = department;

When we use strongly typed views, we can use the @Html.DropDownListFor() method. This helper method will need the list of departments to first populate the dropdown and then set the employee’s department id passed in model object as selected item.

    public ActionResult edit(int id)
{
    Employee emp = db.Employees.Where(e => e.EmployeeId == id).FirstOrDefault();
    ViewBag.DepartmentListItems = db.Departments.Distinct().Select(i => new SelectListItem() { Text = i.DepartmentName, Value = i.DepartmentId.ToString() }).ToList();
    return View(emp);
}

The list items in view bag will be used to bind the dropddownlist and html helper will set the DepartmentId based on the Employee model passed to the view. View Code below.

@Html.DropDownListFor(model => model.DepartmentId, ViewBag.DepartmentListItems as IEnumerable<SelectListItem>,"Select")
Related