Sending the value of a selected option from the view to the controller in .NET 6 using a for loop

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!

Answer №1

When troubleshooting, simply press F12 to inspect the name attribute of your selectlist. You'll notice that they all have the same name/id:

https://i.sstatic.net/rYgum.png

As for resolving this issue:

Include the property in your viewmodel:

public List<int> ShiftIds { get; set; }

Update your razorview accordingly:

<select class="form-select" asp-for="ShiftIds[i]" asp-items="@(new SelectList(Model.Shifts,"Id","ShiftName"))">
            </select>

Outcome:

https://i.sstatic.net/ben7V.png

https://i.sstatic.net/TQITZ.png

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

modify the values of directive elements using a templateUrl

HTML Template: I have an element in the template file seats.tpl.html like this: <select id="guest_table"> <option tables="emptySeats" ng-repeat="table in emptySeats" value="{{table.tableId}}">{{table.tableNumber}}</option& ...

Displaying both columns in an ASP.NET application can be challenging when using the Eval() method, especially

Is there a way to conditionally display an additional table row and column with data if another value from Eval() is not null? This is what I have in my ASPX file: <%# Eval("TwoColumns").ToString() == null ? " " : Eval("Column2Data").ToString() %> ...

Would you suggest using angularjs for authentication in large-scale applications?

As I continue to learn and utilize the AngularJS framework, I have noticed that while some of its features are impressive, some key aspects make it challenging for authentication-based applications. For example, let's consider a scenario where a webs ...

Struggling to incorporate async/await and facing difficulty exporting variables. Any assistance would be greatly appreciated

Issue: I have been struggling for the past two days to resolve this problem on my own. Despite looking at examples from various sources, including different websites, I still can't figure it out. Whenever I attempt to add callbacks or async/await, I h ...

When the function is clicked, an error occurs that says: "return is a reserved word"

I am attempting to trigger a popup window when clicking on the link button, but I keep getting an error stating that "return" is a keyword and expecting an identifier. I'm using ASP.NET for this functionality. <asp:LinkButton ID="CommentAction" h ...

What is the best way to ensure Federated signout redirects to the login page?

Utilizing the WSFederationAuthentication module for authentication, I am seeking a solution whereby after the user clicks the logout button, they are signed out (with all cookies deleted) and redirected to the login page. Below is the code snippet for the ...

"The powerful trio of Moongose, expressjs, and node-webkit combine forces

I'm currently in the process of developing an app using node-webkit, with expressjs and mongoose as the foundation. As a newcomer to this technology stack, I've encountered some challenges. One specific issue involves my attempt to integrate a m ...

Exploring the jQuery Solution for Enhancing Dojo Widget Framework

My experience with Dojo in the past has been great, especially with its widget infrastructure. Being able to easily separate code and HTML content, having a seamless connection with the require system used by Dojo, and the convenient builder that compresse ...

The value from the textbox is not being received by the JavaScript and PHP

I'm encountering an issue with my codes where they are not properly passing the value of the verification code from the textbox to JavaScript and then to PHP. I need assistance in resolving this issue. Below is the snippet of code: HTML: /* HTML c ...

JavaScript personalized video controls. Silence the video by manipulating the input range element

As a newcomer to javascript, I am working on creating custom video controls using js. One issue I am facing is with a span element that contains a mute/unmute icon. When I hover over this span element, a child element appears with an input range bar for ad ...

Aligning text using Javascript and dynamically resizing it with css3 viewport causes a choppy effect when adjusting the size

I'm encountering some issues with keeping my text centered and smoothly resizing when the window size changes. I have a weather website that showcases only the temperature. I present the temperature in various ways. I utilize local storage to store t ...

How can you achieve a seamless or infinite scrolling effect on a webpage?

My idea is as follows: Imagine a long web page where, instead of the scrolling coming to an abrupt stop when the user reaches the end, I want the page to reload from the bottom and allow the scrolling to continue seamlessly. Specifics Picture this - as ...

What is the functionality of the post method in PHP?

Is there a solution to this issue? //error_reporting(0); $token = $_POST['token']; $invite = $_POST['invite']; $url = "https://mywebsite.com/asd/".$invite.""; $dingaling = "$token" ?> When: ERROR: Notice: Undefined index: token ...

How can I delete the onmouseover function in HTML?

Is there a way to remove the (onmouseover="mouseoversound.playclip()") function from the following HTML code? <a href="roster.html" onmouseover="mouseoversound.playclip()">Roster</a> Can we instead implement this functionality in a JavaScript ...

Tips for showcasing timestamps within a Vue.js/Firebase application

In my current project, I am working on developing a chat application using Vue.js and Firebase. The codebase I am referring to can be found at https://github.com/jsfanatik/vuestacks-chat-vue-firebase. I have successfully implemented the Chat component to a ...

Showcasing data from JavaScript, PHP, and MySQL in an organized list

I am having trouble displaying data from MySQL using PHP and JavaScript. I have successfully displayed the data on the page but am facing issues sending it to the script. Below are my files: script1.js $(document).ready( function() { done(); }); functi ...

Obtaining a roster of file names with the help of the Glob

I'm attempting to gather a list of file names in node, however I believe I am encountering a scoping problem. var files = []; glob(options.JSX_DEST + "/*.js", function (er, files) { files = files.map(function(match) { return path.relati ...

Adding an outline to a child mesh in three.js is a simple process

I am interested in adding an outline to meshes. To achieve this, I followed an example that involved creating a new mesh with the same geometry and scaling it. You can find the example here. var outlineMaterial = new THREE.MeshBasicMaterial({ ...

What is the proper method for securing this?

Trying to retrieve 'this' within a method that is invoked by pressing a button, where this points to both the class and the pressed button: p.myVar = 'apple'; $('.go').on('click', this._init); p._init = function(e ...

"Exploring the world of Angular JS through testing controllers with jasmine

I'm currently facing an issue with my test in the controllersSpec.coffee Angular App code: describe 'Controllers', -> beforeEach -> angular.module 'app' describe 'MainCtrl', -> beforeEach inject ($co ...