Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiselect list not showing selected items in c# mvc using linq2sql

I've tried many different ways to pass the selected items to the multiselect list with no luck. Finally, I tried this, which I think should display all the items as selected and still nothing in the list is selected.

public MultiSelectList Companies { get; private set; }

Companies = MulitSelectList(subcontractRepository.SubcontractCompanies(Subcontract.subcontract_id), "Value", "Text");

in SubcontractRepository.cs:

public IEnumerable<SelectListItem> SubcontractCompanies(Guid id)
{
     return c in db.companies
     select new SelectListItem
     {
          Text = c.company_name,
          Value = c.company_id.ToString(),
          Selected = true
     }
}

in View:

<p>
    <label for="Companies">Company:</label>
    <%= Html.ListBox("Companies", Model.Companies) %>
    <%= Html.ValidationMessage("Companies", "*") %>
</p>
like image 664
RememberME Avatar asked Jan 18 '10 19:01

RememberME


2 Answers

Discovered the issue here. The MultiSelectList must have a different name from the ListBox. Made that change and now both versions of the code work.

like image 117
RememberME Avatar answered Oct 18 '22 19:10

RememberME


MultiSelectList constructor has fourth parameter - selected items. Use it:

http://msdn.microsoft.com/en-us/library/system.web.mvc.multiselectlist.multiselectlist.aspx

Use this code:

public class SelectCompanyItem
{
    public string Name { get; set; }
    public Guid Id { get; set; }
}

public IEnumerable<SelectCompanyItem> SubcontractCompanies(Guid id)
{
     return c in db.companies
     select new SelectCompanyItem
     {
          Name = c.company_name,
          Id = c.company_id
     }
}

var companiesList = subcontractRepository.SubcontractCompanies(Subcontract.subcontract_id);
Companies = new MultiSelectList(companiesList , "Id", "Name", companiesList.Select(a => a.Id));

Does it work?

like image 2
LukLed Avatar answered Oct 18 '22 17:10

LukLed