A small project consisting of 2 classes Appointments
and Department
, I need to be able to select the department name from a dropdown box.
I have tried <select>
and asp-items
, both are returning nullpointerexcpetion
or something similar like ArgumentNullException: Value cannot be null. (Parameter 'items')
Appointment Class
public class Appointment
{
[Key]
public virtual int Id { get; set; }
[Display(Name = "Department")]
public virtual int Dep_Id { get; set; }
public Department Departments{ get; set; }
}
Department class
public class Department
{
[Key]
public virtual int ID { get; set; }
[Required]
public virtual string Name { get; set; }
}
Two controllers using Entity Framework (Web API and MVC) were scaffolded based on these classes and localdb Department
table was filled with some values.
In the MVC controller generated from Appointment
, I created a method
public void PopulateDepartmentsDropDownList()
{
var departmentsQuery = from d in _context.Departments
orderby d.Name
select d;
ViewBag.DepartmentID = new SelectList(departmentsQuery.AsNoTracking(), "ID", "Name");
}
And finally in the Create.cshtml
also generated from Appointment
, these attempts do not work.
<select asp-for="Dep_Id" class="control-label" asp-items=ViewBag.DepartmentID></select>
generates an empty dropdown and
@Html.DropDownList("dep", new SelectList(ViewBag.DepartmentID, "ID", "Name"))
crashes the page.
I am not sticking to any method, any solution that works based on any controller is fine.
I think you are missing to convert variable to List
In the controller:
var departmentsQuery = from d in _context.Departments
orderby d.Name
select d;
List<Department> department = departmentsQuery.ToList();
ViewBag.DepartmentID = new SelectList(department, "ID", "Name");
In the View:
@Html.DropDownList("DepartmentID", (IEnumerable<SelectListItem>)ViewBag.DepartmentID, null, new { @class ="form-control" })
or you can replace the "null" with whatever you want display as default selector, i.e. "Select Department".