简体   繁体   中英

How to create dynamic select box in ASP.NET Core using Entity Framework Core?

I am trying to create a select box that is fed from a database table of employees. I am running ASP.NET Core and using Entity Framework Core in Visual Studio 2022. I am also new to both frameworks.

I get this error:

System.NullReferenceException: 'Object reference not set to an instance of an object.'

This is my code:

// GET: Overtimes/Create
public IActionResult Create()
{
    var EmpRecords = _context.Employees.ToList();
        
    ViewBag.EmpRecords = EmpRecords;

    return View();
}

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");}
}

Model classes:

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; }
}

DbContext:

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);
}

You can try to convert EmpRecords to List<SelectListItem> .And use asp-items=@ViewBag.EmpRecords directly.Here is a demo:

If ID is int type in Employee :

var EmpRecords = _context.Employees.ToList().Select(x => new SelectListItem { Text = x.LastName + ", " + x.FirstName, Value = x.ID + "" });

If ID is string type in Employee :

var EmpRecords = _context.Employees.ToList().Select(x => new SelectListItem { Text = x.LastName + ", " + x.FirstName, Value = x.ID });

Then change your select tag code like this:

<select asp-for="EmployeeId" class="form-control" asp-items=@ViewBag.EmpRecords>
</select>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM