I moved on and then came back to this, but I am still unable to get it to work.
var companiesList = subcontractRepository.SubcontractCompanies(Subcontract.subcontract_id);
IEnumerable<Guid> selectedList = companiesList.Select(a => a.Id);
Companies = new MultiSelectList(companiesList, "Id", "Name", selectedList);
In SubcontractRepository.cs
public class SelectCompanyItem
{
public string Name { get; set; }
public Guid Id { get; set; }
}
public IEnumerable<SelectCompanyItem> SubcontractCompanies(Guid id)
{
return
from c in db.companies
select new SelectCompanyItem
{
Name = c.company_name,
Id = c.company_id
};
}
View:
<p>
<label for="Companies">Company:</label>
<%= Html.ListBox("Companies", Model.Companies) %>
<%= Html.ValidationMessage("Companies", "*") %>
</p>
produced html:
<p>
<label for="Companies">Company:</label>
<select id="Companies" multiple="multiple" name="Companies"><option value="4cf411d0-e111-488b-822f-ea194951cfda">Second Company</option>
<option value="1c21e613-a668-4817-bf6d-73befb8c9dbd">Test Company</option>
</select>
</p>
I found the solution. The ListBox must have a different name from the MultiSelectList. I renamed the MultiSelectList in my original code, and it works. I don't want to even begin to think about the amount of time I spent on this!
Here is an ugly work around for now. Set your ViewData with the values you want selected.
ViewData["Companies"] = new string[] { "guid-1", "guid-2" };
I am still trying to debug and see why this is happening. Suprisingly the Unit test for this use case in the MVC project works fine.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With