Search code examples
c#asp.net.netasp.net-mvcasp.net-mvc-4

.Net MVC 5 Multi-Select List Box


I'm trying to create a multi-select box and so far tried many things.

public class DepartmentDropDown
{
    public int Id { get; set; }
    public string Name { get; set; }
}
public class DeviceUserReportViewModel
{
    public List<int> DepartmentIds { get; set; } 
    public List<DepartmentDropDown> Departments { get; set; } 
}
public IActionResult DeviceUserReport()
{
    IEnumerable<DepartmentDropDown> departments = _unitOfWork.Repository<Department>().Get().Select(s=> new DepartmentDropDown { Id = s.Id, Name = s.Name });
    
    DeviceUserReportViewModel model = new DeviceUserReportViewModel
    {
        Departments = departments
    };
}

And in the DeviceUserReport.cshtml

@Html.ListBoxFor(s => s.DepartmentIds,new MultiSelectList(Model.Departments,"Id","Name"),new { @class = "form-control"})

It still shows the list box like this.

enter image description here


Solution

  • For all developers asking the same question =>

    In a .Net MVC application, without any addition library, most you can do is this:

    enter image description here

    With this jQuery library, you can turn a .Net MVC Multi-Select Box to this :

    enter image description here

    Add this js and css to your application

    And mark your input area as multiselect with $('#mySelectList').multiSelect();

    Note: When used the codes from question, this multi-select list sends a list int in model to server side.