In my ViewModel I have the following two lists (one is used for showing all available categories in the form and the other is used for just the user selected category values):
public List<CategoryViewModel> Categories{ get; set; }
public List<string> SelectedCategoryValues { get; set; }
In my View I have the following inside of one of my forms:
@foreach (var category in Model.Categories) {
<div class="checkbox">
<label><input type="checkbox" name="SelectedCategoryValues"
value="@category.Value">@category.Name</label>
</div>
}
When submitting the form the model binder is correctly binding SelectedCategoryValues list.
However, when loading the page the selected checkboxes are not automatically selecting.
The following code is in my Edit GET Action:
var vm = new ProductEditViewModel()
{
Id = product.Id,
Name = product.Name,
Categories = new List<CategoryViewModel>()
{
new CategoryViewModel() { Name = "Category 1", Value = "category1" },
new CategoryViewModel() { Name = "Category 2", Value = "category2" },
new CategoryViewModel() { Name = "Category 3", Value = "category3" }
},
SelectedCategoryValues = productCategories.Select(c => c.Value).ToList()
};
return View(vm);