send a ViewModel which contains a list with a Html.BeginForm (MVC 4)

余生颓废 提交于 2019-12-01 20:26:03

问题


My viewmodel contains a integer list, the problem I have is that when I send my modified form viewmodel, it is always equal to null.

My ViewModel :

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

Action in my Controller :

For example, I'll try to sum ​​the new values ​​entered into the form, but the sum calculated is always equal to 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 view

  @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


回答1:


You need to index each item in your collection. The issue with your code seems to be the use of foreach. You really want to use for instead and pass in the index with the EditorFor call.

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

This only works for ordered lists that will never change their order. If you want to reorder items I suggest your read Phil Haack's great post on sending lists to the server.

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




回答2:


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:


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

Looks like you are filling your int array with zeroes instead of i's. This should read montest.itemTest.Add(i); .



来源:https://stackoverflow.com/questions/17023504/send-a-viewmodel-which-contains-a-list-with-a-html-beginform-mvc-4

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!