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

2

8

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>
Rhombus answered 18/1, 2010 at 19:53 Comment(2)
What version of mvc you are using? Does field name in view match Model.FieldName?Prosody
1.0 The names are the same. I see the list, it just doesn't have anything selected.Rhombus
R
7

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.

Rhombus answered 28/1, 2010 at 21:31 Comment(0)
T
2

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?

Trefler answered 18/1, 2010 at 20:37 Comment(8)
That was the first way that I attempted to do it. I could not get that to work either. I was hoping that if I figured out what was wrong above, that I could discover what I was doing wrong.Rhombus
So you did something wrong. Don't convert c.company_id to string. It is not needed.Trefler
I know I've done something wrong. I am attempting to learn what. When I do not have the .ToString() it complains "Cannot implicitly convert type 'System.Guid' to 'string'"Rhombus
@Rhombus : This code works for me. I have ListBox with all items selected.Trefler
No, nothing is selected for me.Rhombus
@Rhombus : View looks ok. Do you do the rest as I wrote in my response?Trefler
Yes, I just double checked and everything is exactly like it is in your code.Rhombus
@Trefler - Thanks for the help. I discovered the issue. See my answerRhombus

© 2022 - 2024 — McMap. All rights reserved.