Pass a value from selected option inside for loop from view to controller

عبدالمجيد العتيبي 41 Reputation points
2022-11-08T07:05:13.303+00:00

Hello , I have a view that use for loop and inside it select list when i submit the form the model comes without the selected items

here is my controller

   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();  
                // .ToArray();  
                //ViewBag.Dates = dates;  
                
                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();  
            }  

the view

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

The ViewModel

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

Any help will be appreciated

ASP.NET Core
ASP.NET Core
A set of technologies in the .NET Framework for building web applications and XML web services.
4,291 questions
C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
10,496 questions
{count} votes

Accepted answer
  1. Zhi Lv - MSFT 32,056 Reputation points Microsoft Vendor
    2022-11-09T06:56:00.073+00:00

    Hi @عبدالمجيد العتيبي ,

    From your view code, I think when you submit the form, the date and the selected Employee and Shifts should keep the relationships, is that correct? But by using the EmpShifts model, when submit the form, we can't keep relationships. So, I suggest you could create a new model to store the date, employeeid and shiftid (you can also add other property).

    Change the model like this:

    public class EmpShifts  
    {  
        public int DepartmentID { get; set; }  
    
        public List<Departments>? Departments { get; set; } //used to populate the Departments DropDownList.  
        public List<Employee>? Employees { get; set; } = new List<Employee>();//used to populate the Employee DropDownList.  
        public List<Shifts>? Shifts { get; set; } = new List<Shifts>();//used to populate the Shifts DropDownList.  
    
        public List<string> Dates { get; set; } //use for statement to loop the date  
    
        public List<EmpShiftSelected>? EmpShiftSelected { get; set; }  //use this list to transfer the table row data to the controller.  
    
        public int EmployeeID { get; set; }  
        public int ShiftsID { get; set; }  
    }  
    
    public class EmpShiftSelected  
    {  
        public string Date { get; set; }  
        public int EmployeeID { get; set; }    
        public int ShiftsID { get; set; }  
    }  
    

    Then, in the controller:

    258510-image.png

    And the View code like this: pay attention to the name attribute.

    258597-image.png

    You can view the controller and view code from here: 258587-sourcecode.txt

    After that the result as below:
    258632-1.gif


    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    Best regards,
    Dillion

    1 person found this answer helpful.

1 additional answer

Sort by: Most helpful
  1. Bruce (SqlWork.com) 59,131 Reputation points
    2022-11-08T18:46:07.477+00:00

    you are posting back an array of EmployeeId and ShiftId. the post back model should look like:

         public class EmpShiftsPostBackModel   
         {   
             public int[] EmployeeID { get; set; }   
             public int[] ShiftsID { get; set; }   
         }   
    

    the third <select> has no name, so will not be included in post back data. there are no other named form elements, so the above model is complete. if you want additional data consider hidden fields

    0 comments No comments