The approach you are using is correct. I agree with you in using always viewmodels and never ViewBag.
You
In your viewmodel you should change your dictionary to MultiSelectList so you can have
The missing part is in your Html the selected values also.
public IList<int> PriorInsuranceCompaniesSelected { get; set; }
public MultiSelectList PriorInsuranceCompanies { get; set; }
You have to simply outputthen map the list of Checkboxes in afirst field if some Ids are already selected (info that you get when loading data from your repo for loop. Then, on post,example) and the ModelBinder will mapsecond with all the correct objects to your model automagicallyvalues.
Somthing similar to thisFrom your controller in the Get part (just some code as an example):
@foreach model.PriorInsuranceCompaniesSelected = new List<int>();
var checkcompanies = repository.GetPriorInsuranceCompanies();
//add to your PriorInsuranceCompaniesSelected the values already checked from your entity
var entity = repository.GetEntityBy(id);
if (entity.PriorInsuranceCompanies != null)
foreach (var item in Modelentity.InsuranceCompaniesPriorInsuranceCompanies)
model.PriorInsuranceCompaniesSelected.Add(item.Id);
var select = (from s in companies select new {
Id <input= type='checkbox's.Id, name='InsuranceCompanies'Name value='@item= s.Key'>@itemName }).ValueOrderBy(x => x.Name); //.ToList;
<inputmodel.Settori type='checkbox'= name='InsuranceCompanies'new value='@itemMultiSelectList(select, "Id", "Name", model.Key'>@itemPriorInsuranceCompaniesSelected);
Then in your Html you will have an output like this
@foreach (var item in Model.ValuePriorInsuranceCompanies)
{
<label for="@item.Value" class="check">
<input type='checkbox'type="checkbox" name='InsuranceCompanies'id="@item.Value" value='@itemname="PriorInsuranceCompaniesSelected" value="@item.Key'>@itemValue" @(item.ValueSelected ? "checked" : "") />@item.Text</label>
}
Then, on post, the ModelBinder will map the correct objects to your model automagically. you simply have to check values in model.PriorInsuranceCompaniesSelected
This should give you an idea of what to do. I hope it helps