You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将ASP.NET MVC下拉框改为带复选框的多选下拉框

Convert Single-Select Dropdown to Multi-Select with Checkboxes in ASP.NET MVC

Let's break this down into two straightforward parts: updating your controller to use MultiSelectList, then implementing the checkbox-enabled dropdown in your view. Here's how to do it step by step:

Step 1: Convert SelectListItem Collection to MultiSelectList in Controller

Your existing code generates a SelectListItem collection, which is easy to wrap into a MultiSelectList. The MultiSelectList constructor accepts your collection, plus the names of the properties to use for Value and Text (which are already Value and Text on SelectListItem). If you need pre-selected values, you can add a fourth parameter for that.

Here's the modified controller code:

// Generate your SelectListItem collection as before
var eventCategories = ViewBag.EventContentTypeName == EventContentTypeString.Events.Value 
    ? _commonService.GetEventCategoriesModel()
          .Where(category => category.OptionText != "Camp Kaufmann")
          .Select(i => new SelectListItem() { Text = i.OptionText, Value = i.OptionValue.ToString() }) 
    : _commonService.GetEventCategoriesModel()
          .Select(i => new SelectListItem() { Text = i.OptionText, Value = i.OptionValue.ToString() });

// Convert to MultiSelectList
// Add a 4th parameter like new[] { "1", "3" } if you need pre-selected items
ViewBag.EventCategories = new MultiSelectList(eventCategories, "Value", "Text");

Step 2: Implement Checkbox Multi-Select Dropdown in View

Native HTML dropdowns don't support checkboxes out of the box, so we'll use Bootstrap Multiselect—a lightweight, Bootstrap-compatible plugin that integrates seamlessly with your existing form styling.

Step 2.1: Update the View Markup

Replace your existing dropdown code with a ListBox (designed for multi-select) and add the necessary classes for the plugin:

@if (ViewBag.EventContentTypeId == Convert.ToInt32(EventContentType.Events)) { 
<div class="col-sm-3 form-group input" style="padding-left:0"> 
    <div class="input-group"> 
        @Html.ListBox("EventCategoryDDL", ViewBag.EventCategories as MultiSelectList, 
            new { @class = "form-control multiselect", multiple = "multiple" }) 
        <span class="input-group-addon"> 
            <i class="fa fa-file-text" aria-hidden="true"></i> 
        </span> 
    </div> 
</div> 
}

Step 2.2: Add Plugin Resources and Initialization

Include the Bootstrap Multiselect CSS and JS files (make sure the paths match your project's structure), then initialize the plugin with helpful settings:

<!-- Add these after Bootstrap and jQuery in your layout or view -->
<link rel="stylesheet" href="~/Content/bootstrap-multiselect.css" />
<script src="~/Scripts/bootstrap-multiselect.js"></script>

<script>
    $(document).ready(function() {
        $('.multiselect').multiselect({
            includeSelectAllOption: true, // Add a "Select All" checkbox
            enableFiltering: true, // Add a search bar to filter options
            maxHeight: 300, // Limit dropdown height for better usability
            buttonWidth: '100%', // Match the button width to your form control
            nonSelectedText: "-- Select Category --" // Default placeholder text
        });
    });
</script>

Step 3: Handle Form Submission in Controller

When the form is submitted, selected values are sent as an array. Receive them in your action method using an IEnumerable<int> or string[] parameter:

[HttpPost]
public ActionResult YourActionName(IEnumerable<int> EventCategoryDDL, /* Other form parameters */)
{
    // Process the selected category IDs
    if (EventCategoryDDL != null)
    {
        foreach (int categoryId in EventCategoryDDL)
        {
            // Your logic here (e.g., save to database, filter results)
        }
    }

    // Redirect or return view as needed
    return RedirectToAction("Index");
}

Quick Notes

  • Alternative Plugins: If you don't use Bootstrap, you can try Select2 (configured for multi-select with checkboxes) or Chosen, but Bootstrap Multiselect is the most straightforward for checkbox-style dropdowns.
  • Custom Implementation: If you want to avoid plugins, you'd need to build a custom dropdown with HTML checkboxes and JavaScript to sync selected values with a hidden input. This is more work and less maintainable, so plugins are recommended.

内容的提问来源于stack exchange,提问作者kumar swamy

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 08:01:43