When I populate a view with a list of employees and shifts in the view model, I use a for loop to iterate through the dates and select lists for both employees and shifts. However, when I submit the form, the model only captures the first selection instead of all selected items.
Here is the controller code:
public async Task<IActionResult> GetSheduleWithEmp(int DepartmentId, DateTime Start, DateTime End)
{
List<string> dates = Enumerable.Range(0, 1 + End.Subtract(Start).Days)
.Select(i => Start.AddDays(i).ToString("dd-MM-yyyy"))
.ToList();
if (DepartmentId != 0)
{
var Shifts = await eRDbContext.Shifts.ToListAsync();
var model = await eRDbContext.Employees.Where(x => x.DepartmentId == DepartmentId).ToListAsync();
EmpShifts EmpShiftsView = new EmpShifts
{
DepartmentID = DepartmentId,
Employees= model,
Shifts = Shifts,
Dates = dates
};
return View("AddEmployeeToShifts", EmpShiftsView);
}
return View();
}
And here is the view code:
<form asp-action="SaveShifts" class="form" method="post">
@if (Model.Dates != null)
{
<table class="table table-striped">
<thead>
<tr>
<th>Date</th>
<th>Emplyoee</th>
<th>Shift</th>
<th>Priorety</th>
</tr>
</thead>
<tbody>
@for (int i = 0; i < Model.Dates.Count; i++)
{
<tr>
<td>
@Model.Dates[i]
</td>
<td>
<select class="form-select" asp-for="EmployeeID" asp-items="@(new SelectList(Model.Employees,"Id","Name"))">
<option>Please Select Employee</option>
</select>
</td>
<td>
<select class="form-select" asp-for="ShiftsID" asp-items="@(new SelectList(Model.Shifts,"Id","Name"))">
</select>
</td>
<td>
<select>
<option value="1st Oncall">1st Oncall</option>
<option value="2nd Oncall">2nd Oncall</option>
<option value="3rd Oncall">3rd Oncall</option>
</select>
</td>
</tr>
}
</tbody>
</table>
<div class="col-12">
<button type="submit" class="btn btn-primary mx-auto">Submit</button>
</div>
}
</form>
Finally, the ViewModel structure:
public class EmpShifts
{
public int DepartmentID { get; set; }
public IEnumerable<Departments>? Departments { get; set; }
public int EmployeeID { get; set; }
public IEnumerable<Employee>? Employees { get; set; } = new List<Employee>();
public int ShiftsID { get; set; }
public IEnumerable<Shifts>? Shifts { get; set; } = new List<Shifts>();
public List<string> Dates { get; set; }
}
I would appreciate any help with this issue. Thank you!