2017-09-27 54 views
0

我創建的應用程序是員工輸入他們的名/姓,從下拉列表中選擇他們的Department和Appointment。 CRUD操作一切正常。ASP.NET Core 2.0檢索/刪除DropDownList值

但是,我需要從約會下拉列表中刪除已分配給員工的值。每個約會只能有一名員工。所以,我需要在用戶選擇一個後從Appointments下拉列表中刪除Appointments。

我使用ASP.NET 2.0的核心,C#,EntityFrameworkCore代碼第一次和SQL Server 2016

我附上我的代碼,我現在如果有人能盡力協助。先謝謝你!

模型

public class Employee 
{ 
    public int EmployeeID { get; set; } 
    public string FirstName { get; set; } 
    public string LastName { get; set; } 

    public int DepartmentID { get; set; } 
    public Department Department { get; set; } 

    public int AppointmentID { get; set; } 
    public Appointment Appointment { get; set; } 
} 

public class Department 
{ 
    public int DepartmentID { get; set; } 
    public string Name { get; set; } 

    public ICollection<Employee> Employees { get; set; } 
} 

public class Appointment 
{ 
    public int AppointmentID { get; set; } 
    public string TimeSlot { get; set; } 

    public ICollection<Employee> Employees { get; set; } 
} 

的ViewModels

public class EmployeeFormVM 
{ 
    public int EmployeeID { get; set; } 

    [Required(ErrorMessage = "Please enter your First Name")] 
    [Display(Name = "First Name")] 
    [StringLength(50)] 
    public string FirstName { get; set; } 

    [Required(ErrorMessage = "Please enter your Last Name")] 
    [Display(Name = "Last Name")] 
    [StringLength(50)] 
    public string LastName { get; set; } 

    [Required(ErrorMessage = "Please select your Department")] 
    [Display(Name = "Department")] 
    public int DepartmentID { get; set; } 

    public IEnumerable<Department> Departments { get; set; } 

    [Required(ErrorMessage = "Please select your Appointment")] 
    [Display(Name = "Appointment")] 
    public int AppointmentID { get; set; } 

    public IEnumerable<Appointment> Appointments { get; set; } 
} 

的DbContext

public class WinTenDbContext : DbContext 
{ 
    public WinTenDbContext(DbContextOptions<WinTenDbContext> options) : base(options) 
    { 
    } 

    public DbSet<Employee> Employees { get; set; } 
    public DbSet<Department> Departments { get; set; } 
    public DbSet<Appointment> Appointments { get; set; } 

    protected override void OnModelCreating(ModelBuilder modelBuilder) 
    { 
     modelBuilder.Entity<Employee>() 
      .HasKey(e => e.EmployeeID); 

     modelBuilder.Entity<Employee>() 
      .Property(e => e.FirstName) 
      .HasColumnType("varchar(50)") 
      .HasMaxLength(50) 
      .IsRequired(); 


     modelBuilder.Entity<Employee>() 
      .Property(e => e.LastName) 
      .HasColumnType("varchar(50)") 
      .HasMaxLength(50) 
      .IsRequired();    

     modelBuilder.Entity<Department>() 
      .HasKey(d => d.DepartmentID); 

     modelBuilder.Entity<Department>() 
      .Property(d => d.Name) 
      .HasColumnType("varchar(50)") 
      .HasMaxLength(50); 

     modelBuilder.Entity<Appointment>() 
      .HasKey(a => a.AppointmentID); 

     modelBuilder.Entity<Appointment>() 
      .Property(a => a.TimeSlot) 
      .HasColumnType("varchar(50)") 
      .HasMaxLength(50); 
    } 
} 

EmployeesController

public class EmployeesController : Controller 
{ 
    private readonly WinTenDbContext _context; 

    public EmployeesController(WinTenDbContext context) 
    { 
     _context = context; 
    } 

    // GET: Employees and their Departments 
    public async Task<IActionResult> Index() 
    { 
     var webAppDbContext = _context.Employees.Include(d => d.Department).Include(a => a.Appointment); 
     return View(await webAppDbContext.ToListAsync()); 
    } 

    // GET: Employees/Details/5 
    public async Task<IActionResult> Details(int? id) 
    { 
     if (id == null) 
     { 
      return NotFound(); 
     } 

     var employee = await _context.Employees 
      .SingleOrDefaultAsync(m => m.EmployeeID == id); 
     if (employee == null) 
     { 
      return NotFound(); 
     } 

     return View(employee); 
    } 

    // GET: Employees/Create 
    public IActionResult Create() 
    { 
     var departments = _context.Departments.ToList(); 
     var appointments = _context.Appointments.ToList(); 

     var viewModel = new EmployeeFormVM 
     { 
      Departments = departments, 
      Appointments = appointments 
     }; 

     return View(viewModel); 
    } 

    // POST: Employees/Create 
    // To protect from overposting attacks, please enable the specific properties you want to bind to, for 
    // more details see http://go.microsoft.com/fwlink/?LinkId=317598. 
    [HttpPost] 
    [ValidateAntiForgeryToken] 
    public async Task<IActionResult> Create(EmployeeFormVM employee) 
    { 
     if (ModelState.IsValid) 
     { 
      var emp = new Employee(); 
      { 
       emp.FirstName = employee.FirstName; 
       emp.LastName = employee.LastName; 
       emp.DepartmentID = employee.DepartmentID; 
       emp.AppointmentID = employee.AppointmentID; 
      } 

      // Query DB to check if Employee exists with same First/Last Name 
      Employee existingEmployee = await _context.Employees.SingleOrDefaultAsync(m => m.FirstName == employee.FirstName && m.LastName == employee.LastName); 
      if (existingEmployee != null) 
      { 
       // Display Error if duplicate employee 
       ModelState.AddModelError(string.Empty, "An employee with this name has already registered"); 
       employee.Departments = _context.Departments.ToList(); 
       employee.Appointments = _context.Appointments.ToList(); 
       return View(employee); 
      } 

      // Query DB to check if appointment has already been assigned to an employee 
      Employee existingAppointment = await _context.Employees.SingleOrDefaultAsync(m => m.AppointmentID == employee.AppointmentID); 
      if (existingAppointment != null) 
      { 
       // Display error if the appointment was already chosen 
       ModelState.AddModelError(string.Empty, "This appointment has already been taken. Please select another timeslot."); 
       employee.Departments = _context.Departments.ToList(); 
       employee.Appointments = _context.Appointments.ToList(); 
       return View(employee); 
      } 

      _context.Add(emp); 
      await _context.SaveChangesAsync(); 
      return RedirectToAction(nameof(Index)); 
     } 
     return View(employee); 
    } 

    // GET: Employees/Edit/5 
    public async Task<IActionResult> Edit(int? id) 
    { 
     if (id == null) 
     { 
      return NotFound(); 
     } 

     var employeevm = new EmployeeFormVM(); 
     { 
      Employee employee = await _context.Employees.SingleOrDefaultAsync(m => m.EmployeeID == id); 

      if (employee == null) 
      { 
       return NotFound(); 
      } 

      employeevm.EmployeeID = employee.EmployeeID; 
      employeevm.FirstName = employee.FirstName; 
      employeevm.LastName = employee.LastName; 

      // Retrieve list of Departments 
      var departments = _context.Departments.ToList(); 
      employeevm.Departments = departments; 
      // Set the selected department 
      employeevm.DepartmentID = employee.DepartmentID; 

      // Retrieve list of Appointments 
      var appointments = _context.Appointments.ToList(); 
      employeevm.Appointments = appointments; 
      // Set the selected department 
      employeevm.AppointmentID = employee.AppointmentID; 
     } 
     return View(employeevm); 
    } 

    // POST: Employees/Edit/5 
    // To protect from overposting attacks, please enable the specific properties you want to bind to, for 
    // more details see http://go.microsoft.com/fwlink/?LinkId=317598. 
    [HttpPost] 
    [ValidateAntiForgeryToken] 
    public async Task<IActionResult> Edit(EmployeeFormVM vmEdit) 
    { 
     if (ModelState.IsValid) 
     { 
      Employee employee = _context.Employees.SingleOrDefault(e => e.EmployeeID == vmEdit.EmployeeID); 

      if (employee == null) 
      { 
       return NotFound(); 
      } 

      employee.FirstName = vmEdit.FirstName; 
      employee.LastName = vmEdit.LastName; 
      employee.DepartmentID = vmEdit.DepartmentID; 
      employee.AppointmentID = vmEdit.AppointmentID; 

      try 
      { 
       _context.Update(employee); 
       await _context.SaveChangesAsync(); 
      } 
      catch (DbUpdateConcurrencyException) 
      { 
       if (!EmployeeExists(vmEdit.EmployeeID)) 
       { 
        return NotFound(); 
       } 
       else 
       { 
        throw; 
       } 
      } 
      return RedirectToAction(nameof(Index)); 
     } 
     return View(vmEdit); 
    } 

    // GET: Employees/Delete/5 
    public async Task<IActionResult> Delete(int? id) 
    { 
     if (id == null) 
     { 
      return NotFound(); 
     } 

     var employee = await _context.Employees 
      .SingleOrDefaultAsync(m => m.EmployeeID == id); 
     if (employee == null) 
     { 
      return NotFound(); 
     } 

     return View(employee); 
    } 

    // POST: Employees/Delete/5 
    [HttpPost, ActionName("Delete")] 
    [ValidateAntiForgeryToken] 
    public async Task<IActionResult> DeleteConfirmed(int id) 
    { 
     var employee = await _context.Employees.SingleOrDefaultAsync(m => m.EmployeeID == id); 
     _context.Employees.Remove(employee); 
     await _context.SaveChangesAsync(); 
     return RedirectToAction(nameof(Index)); 
    } 

    private bool EmployeeExists(int id) 
    { 
     return _context.Employees.Any(e => e.EmployeeID == id); 
    } 
} 

創建視圖

@using (Html.BeginForm("Create", "Employees")) 
    { 
     @Html.ValidationSummary(true, "", new { @class = "validation-summary-errors" }) 
     //@Html.ValidationSummary(true, "", new { @style = "color: #cc0000" }) 
     //@Html.ValidationSummary(true) 

     <div class="form-group"> 
      @Html.LabelFor(e => e.FirstName) 
      @Html.TextBoxFor(e => e.FirstName, new { @class = "form-control" }) 
      @Html.ValidationMessageFor(e => e.FirstName) 
     </div> 

     <div class="form-group"> 
      @Html.LabelFor(e => e.LastName) 
      @Html.TextBoxFor(e => e.LastName, new { @class = "form-control" }) 
      @Html.ValidationMessageFor(e => e.LastName) 
     </div> 

     <div class="form-group"> 
      @Html.LabelFor(d => d.DepartmentID) 
      @Html.DropDownListFor(d => d.DepartmentID, new SelectList(Model.Departments, "DepartmentID", "Name"), "", new { @class = "form-control" }) 
      @Html.ValidationMessageFor(d => d.DepartmentID) 
     </div> 

     <div class="form-group"> 
      @Html.LabelFor(a => a.AppointmentID) 
      @Html.DropDownListFor(a => a.AppointmentID, new SelectList(Model.Appointments, "AppointmentID", "TimeSlot"), "", new { @class = "form-control" }) 
      @Html.ValidationMessageFor(a => a.AppointmentID) 
     </div> 

     <div class="form-group"> 
      <button type="submit" class="btn btn-primary">Submit</button> 
     </div> 
    } 

編輯視圖

@using (Html.BeginForm("Edit", "Employees")) 
    { 
     <div class="form-group"> 
      @Html.LabelFor(e => e.FirstName) 
      @Html.TextBoxFor(e => e.FirstName, new { @class = "form-control" }) 
      @Html.ValidationMessageFor(e => e.FirstName) 
     </div> 

     <div class="form-group"> 
      @Html.LabelFor(e => e.LastName) 
      @Html.TextBoxFor(e => e.LastName, new { @class = "form-control" }) 
      @Html.ValidationMessageFor(e => e.LastName) 
     </div> 

     <div class="form-group"> 
      @Html.LabelFor(d => d.DepartmentID) 
      @Html.DropDownListFor(d => d.DepartmentID, new SelectList(Model.Departments, "DepartmentID", "Name"), "", new { @class = "form-control" }) 
      @Html.ValidationMessageFor(d => d.DepartmentID) 
     </div> 

     <div class="form-group"> 
      @Html.LabelFor(a => a.AppointmentID) 
      @Html.DropDownListFor(a => a.AppointmentID, new SelectList(Model.Appointments, "AppointmentID", "TimeSlot"), "", new { @class = "form-control" }) 
      @Html.ValidationMessageFor(a => a.AppointmentID) 
     </div> 

     @Html.HiddenFor(e => e.EmployeeID) 

     <div class="form-group"> 
      <button type="submit" class="btn btn-primary">Submit</button> 
     </div> 
    } 
+0

添加一個字段isFilled,當僱員選擇一個約會,你填充它並過濾該 –

+0

@ johnny5,有沒有一種方法或查詢當它首次檢索約會值時,我可以首先檢查Employees表,並僅根據AppointmentID加載不在Employees表中的Appointment值。 – Brian

+0

@Brian,你能否重新評論你的評論?您是否只想過濾沒有關聯員工的約會? – ironstone13

回答

0

你可以使用一個簡單的LINQ查詢象下面這樣:

var appointments = _context.Appointments.Include(x=>x.Employees).Where(x=>!x.Em‌​ployees.Any()).ToLis‌​t(); 

如果您需要重新使用代碼,您可以使用repository pattern並將此代碼提取到另一個類。

每次您需要過濾數據時,例如在GET方法中,您都需要應用該查詢。
對於POST方法,你可能會跳過它,除非:

  1. 你想幹什麼驗證。如果您懷疑用戶可能篡改了輸入,並以某種方式提供了無效的ID,那麼您可能需要再次檢查該過濾的數據。
  2. 你想管理併發 - 假設兩個用戶同時請求該頁面,並且特定的預約插槽可用。如果兩個這些員工選擇了相同的時間段?在這種情況下,檢查POST會有幫助,以防止無效數據
相關問題