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

前端 未结 3 1076
鱼传尺愫
鱼传尺愫 2021-01-19 07:41

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 :



        
相关标签:
3条回答
  • 2021-01-19 08:20

    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

    0 讨论(0)
  • 2021-01-19 08:36

    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
    }
    

    0 讨论(0)
  • 2021-01-19 08:43
     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); .

    0 讨论(0)
提交回复
热议问题