Pass List of Checkboxes into View and Pull out IEnumerable [duplicate]

You cannot bind to a collection using a foreach loop. Nor should you be manually generating your html, which in this case would not work because unchecked checkboxes do not post back. Always use the strongly typed html helpers so you get correct 2-way model binding.

You have not indicated what you models are, but assuming you have a User and want to select Roles for that user, then create view models to represent what you want to display in the view

public class RoleVM
{
  public int ID { get; set; }
  public string Name { get; set; }
  public bool IsSelected { get; set; }
}
public class UserVM
{
  public UserVM()
  {
    Roles = new List<RoleVM>();
  }
  public int ID { get; set; }
  public string Name { get; set; }
  public List<RoleVM> Roles { get; set; }
}

In the GET method

public ActionResult Edit(int ID)
{
  UserVM model = new UserVM();
  // Get you User based on the ID and map properties to the view model
  // including populating the Roles and setting their IsSelect property
  // based on existing roles
  return View(model);
}

View

@model UserVM
@using(Html.BeginForm())
{
  @Html.HiddenFor(m => m.ID)
  @Html.DisplayFor(m => m.Name)
  for(int i = 0; i < Model.Roles.Count; i++)
  {
    @Html.HiddenFor(m => m.Roles[i].ID)
    @Html.CheckBoxFor(m => m.Roles[i].IsSelected)
    @Html.LabelFor(m => m.Roles[i].IsSelected, Model.Roles[i].Name)
  }
  <input type"submit" />
}

Then in the post method, your model will be bound and you can check which roles have been selected

[HttpPost]
public ActionResult Edit(UserVM model)
{
  // Loop through model.Roles and check the IsSelected property
}

Leave a Comment