简体   繁体   中英

ASP.net mvc view can't bind model with List

I couldn't seem to bind any List from this particular view. My codes are

View:

@for (int ctr2 = 0; ctr2 < Model.AnimalsVM.Count(); )
{
     <tr>
     @for (int ctr = 0; ctr < 5 && ctr2 < Model.AnimalsVM.Count(); ctr++, ctr2++)
     {
     <td class="width50px">@Model.AnimalsVM[ctr2].Name&nbsp;&nbsp;</td>
     <td class="width50px">@Html.TextBoxFor(m => m.AnimalsVM[ctr2].Code)%
     @Html.HiddenFor(m => m.AnimalsVM[ctr2].AnimalID)
     @Html.HiddenFor(m => m.AnimalsVM[ctr2].Name)
     </td>
     }
     </tr>
}

My view model is constructed as this:

public class ConfigureVM
{
    public string Name { get; set; }

    public List<AnimalVM> AnimalsVM = new List<AnimalVM>();

}

public class AnimalVM
{
    public int? AnimalID { get; set; }

    public string Name { get; set; }

    public string Code { get; set; }

    public DateTime? LastUpdated { get; set; }
}

AnimalVM does get binded on post. Can anyone explain why AnimalVM does not get binded during post.

You need a getter and setter on AnimalsVM

public List<AnimalVM> AnimalsVM { get; set; }

and then initialize the collection in a parameterless constructor (or in the controller

public class ConfigureVM
{
  public ConfigureVM()
  {
    AnimalsVM = new List<AnimalVM>();
  }
  public List<AnimalVM> AnimalsVM { get; set; }
  ....
}

Side note: not sure what the purpose of the nested for loop is, but depending on the number of items in AnimalsVM , only the first 5 will bind when you post.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM