简体   繁体   中英

.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.

在此处输入图像描述

For all developers asking the same question =>

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

在此处输入图像描述

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

在此处输入图像描述

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.

Html.ListBoxFor Extension Method creates ListBox control and allows users to select multiple options in one go. It is very useful when you want to get multiple options for the users.

You can define this control as follows: @Html.ListBoxFor(model => model.property, ItemList, object HtmlAttribute) Model => model.property: It contains the ID of selected items ItemList: It is a list of items Object HtmlAttributes: It sets extra attributes to ListBox Control.

Like a multiple-selection list box, a standard list box allows users to select values in a list. However, with a list box, users can select only one item in the list. Like a multiple-selection list box, a list box displays all of the items in the list by default.

Here your code is perfect. so to select multiple item from the list just press Ctrl + mouse click.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM