[英]Getting null reference exception when populating dropdown list in ASP.NET Core Razor Pages
[英]Populating dropdown list returning null pointer exception
一个由 2 个类Appointments
和Department
组成的小项目,我需要能够从下拉框中 select 部门名称。
我试过<select>
和asp-items
,两者都返回nullpointerexcpetion
或类似的东西ArgumentNullException: Value cannot be null. (Parameter 'items')
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 controller 中,我创建了一个方法
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"))
使页面崩溃。
我不坚持任何方法,任何基于任何 controller 的解决方案都可以。
我认为你缺乏像这个问题那样的类型转换。 我现在无法测试它,但我认为这是解决方案。 @Html.DropDownListFor("dep", ViewBag.DepartmentID as SelectList)
我认为您缺少将变量转换为 List
在 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");
在视图中:
@Html.DropDownList("DepartmentID", (IEnumerable<SelectListItem>)ViewBag.DepartmentID, null, new { @class ="form-control" })
或者您可以将“null”替换为您希望显示为默认选择器的任何内容,即“选择部门”。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.