Select2 Dropdown in ASP.NET MVC

Introduction

In many web applications, we use dropdown lists. But normal dropdowns have limitations like:

  • No search option

  • Poor UI

  • Difficult for large data

To solve this, we use Select2.

Select2 is a powerful jQuery-based plugin that converts normal dropdowns into searchable and user-friendly dropdowns.

In this article, you will learn:

  • What Select2 is

  • Why we use it

  • How to use Select2 in ASP.NET MVC

  • Real example with code

What is Select2?

Select2 is a JavaScript plugin that enhances elements.

It provides:

✔ Search inside dropdown
✔ Multi-select option
✔ Better UI
✔ AJAX support

Why Use Select2?

✔ Easy to use
✔ Works with large data
✔ Clean design
✔ Improves user experience

Step 1: Add Select2 Files

Add CDN links in your view:

<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/select2.min.css" rel="stylesheet" />

<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/select2.min.js"></script>

Step 2: Create Dropdown in View

<select id="city" class="form-control">
    <option value="">--Select City--</option>
    <option value="1">Ahmedabad</option>
    <option value="2">Surat</option>
    <option value="3">Rajkot</option>
</select>

Step 3: Apply Select2

<script>
    $(document).ready(function () {
        $("#city").select2();
    });
</script>

Multi-Select Example

<select id="cities" multiple class="form-control">
    <option value="1">Ahmedabad</option>
    <option value="2">Surat</option>
    <option value="3">Rajkot</option>
</select>
$("#cities").select2();

Placeholder Example

$("#city").select2({
    placeholder: "Select City",
    allowClear: true
});

AJAX Data Load Example

Controller

public JsonResult GetCities(string term)
{
    var list = new List<object>
    {
        new { id = 1, text = "Ahmedabad" },
        new { id = 2, text = "Surat" },
        new { id = 3, text = "Rajkot" }
    };

    return Json(list, JsonRequestBehavior.AllowGet);
}

View

$("#city").select2({
    ajax: {
        url: '/Home/GetCities',
        dataType: 'json',
        delay: 250,
        data: function (params) {
            return {
                term: params.term
            };
        },
        processResults: function (data) {
            return {
                results: data
            };
        }
    }
});

Tagging (Custom Input)

$("#city").select2({
    tags: true
});

👉 User can type new values

Set Selected Value

$("#city").val("1").trigger("change");

Common Problems & Solutions

Problem: Not Working

✔ Check jQuery loaded
✔ Check Select2 files

Problem: Dropdown inside Modal

$("#city").select2({
    dropdownParent: $("#myModal")
});
```}