views:

273

answers:

2

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>
+1  A: 

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.

iaimtomisbehave
Thanks, that works. Please let me know if you figure it out. I have had no luck.
RememberME
I discovered the issue. See my answer. Thanks for your help.
RememberME
Ah, makes sense seems like the helper method finds a ViewData entry for Companies and since it is emtpy it doesn't set any fields as selected. Thanks.
iaimtomisbehave
+1  A: 

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!

RememberME