Submit a ViewModel that contains a list with Html.BeginForm (MVC 4)

My viewmodel contains an integer list, the problem is that when submitting a modified viewmodel form, it is always zero.

My ViewModel:

public class testViewModel { public List<int> itemTest { get; set; } 

Action in my controller:

For example, I will try to summarize the new values ​​entered into the form, but the calculated amount is always 0, nothing changes.

  public ActionResult form(int nbre) { testViewModel montest = new testViewModel() { itemTest = new List<int>() }; for(int i=0;i<nbre ;i++) { montest.itemTest.Add(0); } return View(montest); } [HttpPost] [ValidateAntiForgeryToken] public ActionResult form(testViewModel maListe) { int somme = 0; if (maListe.itemTest != null) { if (maListe.itemTest.Count() != 0) { foreach (var item in maListe.itemTest) { somme += item; } } } //listtest = maListe; return RedirectToAction("test2", new { qte = somme }); } 

My opinion

  @model MvcWebRole1.ViewModels.testViewModel @{ ViewBag.Title = "Formulaire"; } @using (Html.BeginForm()) { @Html.AntiForgeryToken() @Html.ValidationSummary(true) <table> @foreach (var item in Model.itemTest) { <tr > <td > @Html.Label("Quantitée") </td> <td> @Html.EditorFor(model => item) @Html.ValidationMessageFor(model => item) </td> </tr> } </table> <input type="submit" value="Valider" /> } 

Thank you, kindly help me

+4
source share
3 answers

You need to index each item in your collection. The problem with your code seems to be using foreach . You really want to use for instead and pass the index by calling EditorFor .

  for (int i = 0; i < Model.Items.Count; i++) { @Html.EditorFor(m => m.Items[i]) } 

This only works for ordered lists that will never reorder. If you want to reorder items, I offer your reader Phil Haack an excellent post when posting lists to the server.

http://haacked.com/archive/2008/10/23/model-binding-to-a-list.aspx

+3
source

list binding

 <form> @for(int i=0;i<Model.itemTest.Count ;i++) { @Html.TextBoxFor(x=>x.itemTest[i]) //or just <input type="text" name="itemTest "/> working to } 

+3
source
  for(int i=0;i<nbre ;i++) { montest.itemTest.Add(0); } return View(montest); 

It looks like you are filling your int array with zeros instead of i. This should read montest.itemTest.Add(i); .

+1
source

Source: https://habr.com/ru/post/1485420/


All Articles