Reputation: 11
I am trying to set up a multiselect list so that I can assign multiple modules to a company. When I create a new company and assign modules, it works correctly. But when I go to edit a company I cannot figure out why the pre-selected modules will not show.
When I debug I can see that it's passing the correct data for both the company and the list of modules but the pre-selected options don't show on the edit page. The selecteditems should be a list, correct?
Any help would be appreciated.
public class Company
{
public int Id { get; set; }
public string Name { get; set; }
}
public class SiteModules
{
public int Id { get; set; }
public string Name { get; set; }
}
public class CompanySiteModules
{
public int CompanyId { get; set; }
public Company Company { get; set; }
public int SiteModuleId { get; set; }
public SiteModule SiteModule { get; set; }
}
In my repository:
public async Task<Company?> GetCompanyById(int id)
{
return await context.Companies
.Include(x => x.SiteModules)
.Include(y => y.CompanyType)
.FirstOrDefaultAsync(x => x.Id == id);
}
public async Task<List<int>> GetAllMods(int id)
{
var modules = await context.CompanySiteModules
.Where(x => x.CompanyId == id)
.ToListAsync();
var modulesList = modules.Select(t => t.SiteModuleId).ToList();
return modulesList;
}
In my controller:
var company = await companyRepository.GetCompanyById(id);
var selectedModules = await companyRepository.GetAllMods(id);
SiteModulesList = new MultiSelectList(context.SiteModules, "Id", "Name", selectedModules)
My page:
<label class="form-label">Modules</label>
<select class="form-select"
asp-items="@Model.SiteModulesList"
asp-for="SiteModulesList"></select>
Upvotes: 0
Views: 23