0

I am posting a form from the view to the controller using Beginform method, and passing a list of id's through a hidden field.

But it returns only the last value in the list.

View.cshtml:

 @using(Html.BeginForm("makepayment","home",FormMethod.Post))
 {
     if (Model != null) 
     {
         for (var i = 0; i < Model.Count; i++) 
         {
             @Html.HiddenFor(m => Model[i].cart.vid)
         }
    }
                               
    @Html.TextBoxFor(m => m[0].payment.cname);
 
    @Html.TextBoxFor(m => m[0].payment.number);
    @Html.TextBoxFor(m => m[0].payment.securitycode);
    @Html.TextBoxFor(m =>m[0].payment.expdate);
    <input type="submit" value="pay" />
 }

It only returns the last value. The loop isn't working because I used IEnumerable, but I don't know how to solve

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
codeseeker
  • 196
  • 1
  • 13

1 Answers1

0

This sounds like a closure problem, see Understanding Closures

Try this:

for (var i = 0; i < Model.Count; i++) {
    var index = i;
    @Html.HiddenFor(m => Model[index].cart.vid)
}
mnemonic
  • 692
  • 1
  • 9
  • 18
  • thank u for your response,But in the controller,i cant put this value in the db,Actually i don't know well how to do this – codeseeker Jul 06 '19 at 15:23
  • public ActionResult makepayment(List c) my controller and payment cart is my viewmodel,how to add this to database?Am using stored procedure? – codeseeker Jul 06 '19 at 15:24
  • Are you referring to the 'index' variable value? If so, you don't need to add it to your database or your controller, it's just a temporary loop variable. This problem has to do with WHEN Lambda functions (in this case the 'm => Model[i].cart.vid' line of code) are executed as well as the scope in which they were created. Here's another link which explains it: https://stackoverflow.com/questions/428617/what-are-closures-in-net – mnemonic Jul 07 '19 at 01:13