AshT
AshT

Reputation: 545

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.

Upvotes: 0

Views: 651

Answers (1)

user3559349
user3559349

Reputation:

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.

Upvotes: 1

Related Questions