如何使用 Entity Framework 核心在 ASP.NET 核心中创建动态 select 框?
How to create dynamic select box in ASP.NET Core using Entity Framework Core?
我正在尝试创建一个 select 框,该框由员工数据库 table 提供。我是 运行 ASP.NET Core 并在 Visual Studio 2022 年使用 Entity Framework Core。我也是这两个框架的新手。
我收到这个错误:
System.NullReferenceException: 'Object reference not set to an instance of an object.'
这是我的代码:
// GET: Overtimes/Create
public IActionResult Create()
{
var EmpRecords = _context.Employees.ToList();
ViewBag.EmpRecords = EmpRecords;
return View();
}
查看:
@model OvertimeTracking.Models.Overtime
@{
ViewData["Title"] = "Create";
}
<h1>Create</h1>
<h4>Overtime</h4>
<hr />
<div class="row">
<div class="col-md-4">
<form asp-action="Create">
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
<div class="form-group">
<label asp-for="Date" class="control-label"></label>
<input asp-for="Date" class="form-control" />
<span asp-validation-for="Date" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="EmployeeId" class="control-label">Employee</label>
<select asp-for="EmployeeId" class="form-control" asp-items="@(new
SelectList(@ViewBag.EmpRecords,"ID","LastName" + ", " + "FirstName"))">
</select>
<span asp-validation-for="EmployeeId" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="Hours" class="control-label"></label>
<input asp-for="Hours" class="form-control" />
<span asp-validation-for="Hours" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="Submitted" class="control-label"></label>
<input asp-for="Submitted" class="form-control" />
<span asp-validation-for="Submitted" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="ModifiedBy" class="control-label"></label>
<input asp-for="ModifiedBy" class="form-control" />
<span asp-validation-for="ModifiedBy" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="Modified" class="control-label"></label>
<input asp-for="Modified" class="form-control" />
<span asp-validation-for="Modified" class="text-danger"></span>
</div>
<div class="form-group">
<input type="submit" value="Create" class="btn btn-primary" />
</div>
</form>
</div>
</div>
<div>
<a asp-action="Index">Back to List</a>
</div>
@section Scripts {
@{await Html.RenderPartialAsync("_ValidationScriptsPartial");}
}
型号类:
public partial class Overtime
{
public int Id { get; set; }
public int EmployeeId { get; set; }
public DateTime? Date { get; set; }
public int? Hours { get; set; }
public int? SubmittedBy { get; set; }
public DateTime? Submitted { get; set; }
public int? ModifiedBy { get; set; }
public DateTime? Modified { get; set; }
}
数据库上下文:
public partial class OvertimeContext : DbContext
{
public OvertimeContext()
{
}
public OvertimeContext(DbContextOptions<OvertimeContext> options)
: base(options)
{
}
public virtual DbSet<Overtime> Overtimes { get; set; } = null!;
public virtual DbSet<Role> Roles { get; set; } = null!;
public virtual DbSet<User> Users { get; set; } = null!;
public virtual DbSet<UserRole> UserRoles { get; set; } = null!;
public virtual DbSet<Employee> Employees { get; set; } = null!;
public virtual DbSet<EmpName> EmpName { get; set; }
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
if (!optionsBuilder.IsConfigured)
{
optionsBuilder.UseSqlServer("Name=DefaultConnection");
}
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Employee>(entity =>
{
entity.HasKey(e => e.Id);
entity.ToTable("employees");
entity.Property(e => e.Id).HasColumnName("ID");
entity.Property(e => e.FirstName)
.HasMaxLength(50)
.IsUnicode(false)
.HasColumnName("firstName");
entity.Property(e => e.LastName)
.HasMaxLength(50)
.IsUnicode(false)
.HasColumnName("lastName");
entity.Property(e => e.PeopleSoft)
.IsUnicode(false)
.HasColumnName("peoplesoft_id");
});
modelBuilder.Entity<Overtime>(entity =>
{
entity.HasKey(e => e.Id);
entity.ToTable("overtime");
entity.Property(e => e.Date)
.HasColumnType("date")
.HasColumnName("date");
entity.Property(e => e.EmployeeId)
.HasColumnName("employee_id");
entity.Property(e => e.Hours).HasColumnName("hours");
entity.Property(e => e.Id)
.ValueGeneratedOnAdd()
.HasColumnName("ID");
entity.Property(e => e.Modified)
.HasColumnType("datetime")
.HasColumnName("modified");
entity.Property(e => e.ModifiedBy).HasColumnName("modified_by");
entity.Property(e => e.Submitted)
.HasColumnType("datetime")
.HasColumnName("submitted");
entity.Property(e => e.SubmittedBy).HasColumnName("submitted_by");
});
modelBuilder.Entity<Role>(entity =>
{
entity.HasKey(e => e.Id);
entity.ToTable("roles");
entity.Property(e => e.Id)
.ValueGeneratedOnAdd()
.HasColumnName("ID");
entity.Property(e => e.Role1)
.HasMaxLength(50)
.IsUnicode(false)
.HasColumnName("role");
});
modelBuilder.Entity<User>(entity =>
{
entity.HasKey(e => e.Id);
entity.ToTable("users");
entity.Property(e => e.Id).HasColumnName("ID");
entity.Property(e => e.Email)
.HasMaxLength(150)
.IsUnicode(false)
.HasColumnName("email");
entity.Property(e => e.FirstName)
.HasMaxLength(50)
.IsUnicode(false)
.HasColumnName("firstName");
entity.Property(e => e.LastName)
.HasMaxLength(50)
.IsUnicode(false)
.HasColumnName("lastName");
entity.Property(e => e.Password)
.IsUnicode(false)
.HasColumnName("password");
entity.Property(e => e.UserName)
.HasMaxLength(50)
.IsUnicode(false)
.HasColumnName("userName");
});
modelBuilder.Entity<UserRole>(entity =>
{
entity.HasNoKey();
entity.ToTable("user_roles");
entity.Property(e => e.Id)
.ValueGeneratedOnAdd()
.HasColumnName("ID");
entity.Property(e => e.RoleId).HasColumnName("role_id");
entity.Property(e => e.UserId).HasColumnName("user_id");
});
OnModelCreatingPartial(modelBuilder);
}
partial void OnModelCreatingPartial(ModelBuilder modelBuilder);
}
你可以尝试将EmpRecords
转换成List<SelectListItem>
。然后使用asp-items=@ViewBag.EmpRecords
directly.Here是一个演示:
如果 ID
是 int
输入 Employee
:
var EmpRecords = _context.Employees.ToList().Select(x => new SelectListItem { Text = x.LastName + ", " + x.FirstName, Value = x.ID + "" });
如果 ID
是 string
输入 Employee
:
var EmpRecords = _context.Employees.ToList().Select(x => new SelectListItem { Text = x.LastName + ", " + x.FirstName, Value = x.ID });
然后像这样更改您的 select 标记代码:
<select asp-for="EmployeeId" class="form-control" asp-items=@ViewBag.EmpRecords>
</select>
我正在尝试创建一个 select 框,该框由员工数据库 table 提供。我是 运行 ASP.NET Core 并在 Visual Studio 2022 年使用 Entity Framework Core。我也是这两个框架的新手。
我收到这个错误:
System.NullReferenceException: 'Object reference not set to an instance of an object.'
这是我的代码:
// GET: Overtimes/Create
public IActionResult Create()
{
var EmpRecords = _context.Employees.ToList();
ViewBag.EmpRecords = EmpRecords;
return View();
}
查看:
@model OvertimeTracking.Models.Overtime
@{
ViewData["Title"] = "Create";
}
<h1>Create</h1>
<h4>Overtime</h4>
<hr />
<div class="row">
<div class="col-md-4">
<form asp-action="Create">
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
<div class="form-group">
<label asp-for="Date" class="control-label"></label>
<input asp-for="Date" class="form-control" />
<span asp-validation-for="Date" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="EmployeeId" class="control-label">Employee</label>
<select asp-for="EmployeeId" class="form-control" asp-items="@(new
SelectList(@ViewBag.EmpRecords,"ID","LastName" + ", " + "FirstName"))">
</select>
<span asp-validation-for="EmployeeId" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="Hours" class="control-label"></label>
<input asp-for="Hours" class="form-control" />
<span asp-validation-for="Hours" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="Submitted" class="control-label"></label>
<input asp-for="Submitted" class="form-control" />
<span asp-validation-for="Submitted" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="ModifiedBy" class="control-label"></label>
<input asp-for="ModifiedBy" class="form-control" />
<span asp-validation-for="ModifiedBy" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="Modified" class="control-label"></label>
<input asp-for="Modified" class="form-control" />
<span asp-validation-for="Modified" class="text-danger"></span>
</div>
<div class="form-group">
<input type="submit" value="Create" class="btn btn-primary" />
</div>
</form>
</div>
</div>
<div>
<a asp-action="Index">Back to List</a>
</div>
@section Scripts {
@{await Html.RenderPartialAsync("_ValidationScriptsPartial");}
}
型号类:
public partial class Overtime
{
public int Id { get; set; }
public int EmployeeId { get; set; }
public DateTime? Date { get; set; }
public int? Hours { get; set; }
public int? SubmittedBy { get; set; }
public DateTime? Submitted { get; set; }
public int? ModifiedBy { get; set; }
public DateTime? Modified { get; set; }
}
数据库上下文:
public partial class OvertimeContext : DbContext
{
public OvertimeContext()
{
}
public OvertimeContext(DbContextOptions<OvertimeContext> options)
: base(options)
{
}
public virtual DbSet<Overtime> Overtimes { get; set; } = null!;
public virtual DbSet<Role> Roles { get; set; } = null!;
public virtual DbSet<User> Users { get; set; } = null!;
public virtual DbSet<UserRole> UserRoles { get; set; } = null!;
public virtual DbSet<Employee> Employees { get; set; } = null!;
public virtual DbSet<EmpName> EmpName { get; set; }
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
if (!optionsBuilder.IsConfigured)
{
optionsBuilder.UseSqlServer("Name=DefaultConnection");
}
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Employee>(entity =>
{
entity.HasKey(e => e.Id);
entity.ToTable("employees");
entity.Property(e => e.Id).HasColumnName("ID");
entity.Property(e => e.FirstName)
.HasMaxLength(50)
.IsUnicode(false)
.HasColumnName("firstName");
entity.Property(e => e.LastName)
.HasMaxLength(50)
.IsUnicode(false)
.HasColumnName("lastName");
entity.Property(e => e.PeopleSoft)
.IsUnicode(false)
.HasColumnName("peoplesoft_id");
});
modelBuilder.Entity<Overtime>(entity =>
{
entity.HasKey(e => e.Id);
entity.ToTable("overtime");
entity.Property(e => e.Date)
.HasColumnType("date")
.HasColumnName("date");
entity.Property(e => e.EmployeeId)
.HasColumnName("employee_id");
entity.Property(e => e.Hours).HasColumnName("hours");
entity.Property(e => e.Id)
.ValueGeneratedOnAdd()
.HasColumnName("ID");
entity.Property(e => e.Modified)
.HasColumnType("datetime")
.HasColumnName("modified");
entity.Property(e => e.ModifiedBy).HasColumnName("modified_by");
entity.Property(e => e.Submitted)
.HasColumnType("datetime")
.HasColumnName("submitted");
entity.Property(e => e.SubmittedBy).HasColumnName("submitted_by");
});
modelBuilder.Entity<Role>(entity =>
{
entity.HasKey(e => e.Id);
entity.ToTable("roles");
entity.Property(e => e.Id)
.ValueGeneratedOnAdd()
.HasColumnName("ID");
entity.Property(e => e.Role1)
.HasMaxLength(50)
.IsUnicode(false)
.HasColumnName("role");
});
modelBuilder.Entity<User>(entity =>
{
entity.HasKey(e => e.Id);
entity.ToTable("users");
entity.Property(e => e.Id).HasColumnName("ID");
entity.Property(e => e.Email)
.HasMaxLength(150)
.IsUnicode(false)
.HasColumnName("email");
entity.Property(e => e.FirstName)
.HasMaxLength(50)
.IsUnicode(false)
.HasColumnName("firstName");
entity.Property(e => e.LastName)
.HasMaxLength(50)
.IsUnicode(false)
.HasColumnName("lastName");
entity.Property(e => e.Password)
.IsUnicode(false)
.HasColumnName("password");
entity.Property(e => e.UserName)
.HasMaxLength(50)
.IsUnicode(false)
.HasColumnName("userName");
});
modelBuilder.Entity<UserRole>(entity =>
{
entity.HasNoKey();
entity.ToTable("user_roles");
entity.Property(e => e.Id)
.ValueGeneratedOnAdd()
.HasColumnName("ID");
entity.Property(e => e.RoleId).HasColumnName("role_id");
entity.Property(e => e.UserId).HasColumnName("user_id");
});
OnModelCreatingPartial(modelBuilder);
}
partial void OnModelCreatingPartial(ModelBuilder modelBuilder);
}
你可以尝试将EmpRecords
转换成List<SelectListItem>
。然后使用asp-items=@ViewBag.EmpRecords
directly.Here是一个演示:
如果 ID
是 int
输入 Employee
:
var EmpRecords = _context.Employees.ToList().Select(x => new SelectListItem { Text = x.LastName + ", " + x.FirstName, Value = x.ID + "" });
如果 ID
是 string
输入 Employee
:
var EmpRecords = _context.Employees.ToList().Select(x => new SelectListItem { Text = x.LastName + ", " + x.FirstName, Value = x.ID });
然后像这样更改您的 select 标记代码:
<select asp-for="EmployeeId" class="form-control" asp-items=@ViewBag.EmpRecords>
</select>