【问题标题】:Populating dropdown list returning null pointer exception填充下拉列表返回空指针异常
【发布时间】:2023-03-11 20:46:01
【问题描述】:

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

我尝试过<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; }
    }

使用实体框架(Web API 和 MVC)的两个控制器是基于这些类构建的,并且 localdb Department 表填充了一些值。 在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");
        }

最后在同样由Appointment生成的Create.cshtml中,这些尝试都不起作用。

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

生成一个空的下拉菜单 和

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

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

【问题讨论】:

标签: c# asp.net-mvc entity-framework drop-down-menu razor-pages


【解决方案1】:

我认为您缺少将变量转换为列表

在控制器中:

var departmentsQuery = from d in _context.Departments
                                   orderby d.Name
                                   select d;
    List<Department> department = departmentsQuery.ToList();
    
    ViewBag.DepartmentID = new SelectList(department, "ID", "Name");

在视图中:

@Html.DropDownList("DepartmentID", (IEnumerable<SelectListItem>)ViewBag.DepartmentID, null, new { @class ="form-control" })

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

【讨论】:

    【解决方案2】:

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

    【讨论】:

      猜你喜欢
      • 2012-02-19
      • 1970-01-01
      • 2014-05-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多