Reputation: 2092
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>
Upvotes: 5
Views: 5780
Reputation: 2092
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!
Upvotes: 8
Reputation: 2743
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.
Upvotes: 1