【发布时间】:2023-03-11 20:46:01
【问题描述】:
一个由Appointments和Department两个类组成的小项目,我需要能够从下拉框中选择部门名称。
我尝试过<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