0

I have an asp.net MVC application. I have a viewmodel that has another nested ViewModel list as part of it..

When I bind my main ViewModel to my page everything renders as expected. In my nested ViewModelList I have a few properties and one of which is boolean that represents a checkbox on my page. When I post my model back to the controller I want to be able to iterate through the nested viewmodellist and validate a boolean value is set to true (represented as a checkbox on my page). The problem is when I do a post the initial list that was rendered on my page is lost so I have no way to capture the values. Since there is no viewstate is there a way to handle this very common scenario. Here are my 2 view models

MainViewModel

public class CreatePersonViewModel
{
    public string FirstName { get; set; }

    public string LastName { get; set; }

    public string MiddleName { get; set; }

   public IEnumerable<CertificationFormsViewModel> forms { get; set; }


}


public class CertificationFormsViewModel
{
    public string FormID{ get; set; }

    public string FormName{ get; set; }

    public string FormContent { get; set; }

    public bool DoAgree { get; set; }


}

I populate the forms property in my CreatePersonViewModel in my main controller and render the model to my page, looping through each form and displaying each with a checkbox that represents the "DoAgree" property.

When I submit the form the CreatePersonViewModel value persists to my POST controller but the nested list is null and consequently the selected checkbox value "DoAgree" is lost. I need to be able to retain the FormID and DoAgree properties so that I can save those to my database. Do I need some kind of hidden field? and if so how can I approach this with a list?

The list is bound in my page as such to display

  @{foreach (var form in Model.forms)
  {
   @Html.CheckBoxFor(forms2 => form.DoAgree)

  }
Scott
  • 153
  • 2
  • 12
  • You cannot use a `foreach` loop to generate form controls for a collection - refer [this answer](http://stackoverflow.com/questions/30094047/html-table-to-ado-net-datatable/30094943#30094943) –  Dec 08 '16 at 21:19
  • Thanks, exactly what I needed – Scott Dec 09 '16 at 01:51

0 Answers0