填充下拉列表返回空指针异常

Populating dropdown list returning null pointer exception

一个由 2 类 AppointmentsDepartment 组成的小项目,我需要能够 select 从下拉框中选择部门名称。

我试过 <select>asp-items,两者都返回 nullpointerexcpetion 或类似 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; }
    }

两个控制器使用 Entity Framework(Web API 和 MVC)基于这些 类 和 localdb Department table 填充了一些值. 在从 Appointment 生成的 MVC 控制器中,我创建了一个方法

        public void PopulateDepartmentsDropDownList()
        {
            var departmentsQuery = from d in _context.Departments
                                   orderby d.Name
                                   select d;
            ViewBag.DepartmentID = new SelectList(departmentsQuery.AsNoTracking(), "ID", "Name");
        }

最后在 Create.cshtml 中也是从 Appointment 生成的,这些尝试都不起作用。

<select asp-for="Dep_Id" class="control-label" asp-items=ViewBag.DepartmentID></select>

生成一个空的下拉列表 和

@Html.DropDownList("dep", new SelectList(ViewBag.DepartmentID, "ID", "Name")) 使页面崩溃。

我不拘泥于任何方法,任何基于任何控制器的解决方案都可以。

我认为您缺少 this 问题中的类型转换。我现在无法测试,但我认为这是解决方案。 @Html.DropDownListFor("dep", ViewBag.DepartmentID as SelectList)

我认为你缺少将变量转换为 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" })

或者您可以将“null”替换为您想要显示为默认选择器的任何内容,即“Select 部门”。