Skip to content

07 Dropdown List

M. Fares edited this page Mar 12, 2018 · 1 revision

Dropdown list in the view can be achieved using ViewBag with the following steps

  1. Fill in the ViewBag with the list of items as follows:
ViewBag.DepartmentId = new SelectList(db.Departments, "Id", "Name");
  1. Add the razor code to the corresponding view
<div class="form-group">
            @Html.LabelFor(model => model.Department, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.DropDownList("DepartmentId", null, htmlAttributes: new { @class = "form-control" })
                @Html.ValidationMessageFor(model => model.DepartmentId, "", new { @class = "text-danger" })
            </div>
        </div>
  1. The first parameter of the Html.DropDownList("DepartmentId", ...) has to have the same name as the ViewBag.DeprtmentId. In addition, your view model should contain the property DepartmentId.

  2. Example: Check the Faculty Controller in the the Create and Edit actions. The Faculty is using the Department DropDownList. See the Faculty create and edit views

Clone this wiki locally