-1

I have a model that brings in user information. I want to submit that information in a form, but I'm having trouble submitting information since regardless of how many items are in the list. It will only submit the first one.

@using (Html.BeginForm("Action", "Controller", FormMethod.Post))
{
   <table>
   foreach(var item in Model)
   {
     <tr>
           <td>@Model.UserName</td>
           <td>@Html.TextBoxFor(a => Model.LoginName})</td>
           <td>@Html.TextBoxFor(a => Model.EmployeeNumber})</td>
           <input type="submit" value="Submit">
     </tr>
   }
   </table>
}

Everything else works, I check the controller and see that the first parameters are being passed in on submit. The list is being populated from a database. I've looked into using SingleOrDefault(), but I don't think that will work in this case.

walangala
  • 231
  • 1
  • 4
  • 15
  • Your are creating the same form controls in each iteration. But you cannot use a `foreach` loop to bind to a collection (refer [this answer](http://stackoverflow.com/questions/30094047/html-table-to-ado-net-datatable/30094943#30094943) for an explanation) –  Jul 04 '18 at 00:04

1 Answers1

1

To submit only first iteration values you can use for loop to put only first index model inside form else not.

if(Model!=null){
for (int i = 0; i < Model.Count; i++)
{
   //Form for 1st model only
   if(i==0){
       @using (Html.BeginForm("Action", "Controller", FormMethod.Post))
       {
       <table> 
       <tr>
       <td>@Model[i].UserName</td>
       <td>@Html.TextBoxFor(a => Model[i].LoginName})</td>
       <td>@Html.TextBoxFor(a => Model[i].EmployeeNumber})</td>
       <input type="submit" value="Submit">
      </tr>
       </table>
       }
    }

    else{
        <table> 
          <tr>
       <td>@Model[i].UserName</td>
       <td>@Html.TextBoxFor(a => Model[i].LoginName})</td>
       <td>@Html.TextBoxFor(a => Model[i].EmployeeNumber})</td>
       <input type="submit" value="Submit">
     </tr>
       </table>
      }
  }

 }
TAHA SULTAN TEMURI
  • 4,031
  • 2
  • 40
  • 66
  • That’s the problem, I was in a rush to figure this out and it’s not always the first iteration, I got it to work a different way though without posting so I changed my code a bit, but this code may be handy for some programmers that may need help with syntax when using a specific model in a view so I’ll upvote it – walangala Jul 04 '18 at 19:58