0

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);

1 Answer 1

1

You need to include something like bool IsSelected{get;set;} into CategoryViewModel and assign values in the controller.

var vm = new ProductEditViewModel()
{
    Id = product.Id,
    Name = product.Name,
    Categories = new List<CategoryViewModel>()
    {
        new CategoryViewModel() { Name = "Category 1", Value = "category1",
         IsSelected = productCategories.Where(c => c.Value == "category1").Count() > 0 ? true : false},
         //do the same
        //new CategoryViewModel() { Name = "Category 2", Value = "category2" },
        //new CategoryViewModel() { Name = "Category 3", Value = "category3" }
    },
    //not required
    //SelectedCategoryValues = productCategories.Select(c => c.Value).ToList()
};

return View(vm);

And in the view

@foreach (var category in Model.Categories) {
     <div class="checkbox">
          <label><input type="checkbox" checked="@category.IsSelected" name="SelectedCategoryValues" 
          value="@category.Value">@category.Name</label>
     </div>
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.