Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why isn't multiselect list showing selected items? MVC

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>
like image 886
RememberME Avatar asked Jan 26 '10 20:01

RememberME


2 Answers

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!

like image 92
RememberME Avatar answered Sep 24 '22 14:09

RememberME


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.

like image 31
sarvesh Avatar answered Sep 25 '22 14:09

sarvesh