Creating a searchable dropdown in ASP.NET MVC can greatly enhance user experience, especially when dealing with large datasets. In this tutorial, we'll go through the steps to implement a searchable dropdown using ASP.NET MVC along with code examples.
Step 1: Setting up the ASP.NET MVC Project
- Open Visual Studio and create a new ASP.NET MVC project.
- Name your project and select a suitable location.
- Choose the .NET Framework version you want to use (e.g., .NET Framework 4.7.2).
- Click "Create" to generate the project structure.
Step 2: Create Model and Mock Data
- Create a model class that represents the data you want to display in the dropdown. For example:
public class Item
{
public int Id { get; set; }
public string Name { get; set; }
}
- For demonstration purposes, create a mock repository to provide data:
public static class ItemRepository
{
public static List<Item> GetItems()
{
return new List<Item>
{
new Item { Id = 1, Name = "Item 1" },
new Item { Id = 2, Name = "Item 2" },
new Item { Id = 3, Name = "Item 3" },
// Add more items as needed
};
}
}
Step 3: Create Controller and Action Method
- Create a controller to handle the requests related to your dropdown. For example:
public class DropdownController : Controller
{
public ActionResult Index()
{
ViewBag.Items = ItemRepository.GetItems();
return View();
}
}
Step 4: Create View
- Create a view for your dropdown. Inside the view, add HTML for the dropdown along with JavaScript for search functionality. Here's an example of the view (
Index.cshtml
):
@{
ViewBag.Title = "Searchable Dropdown";
}
<h2>Searchable Dropdown</h2>
<select id="itemDropdown" class="form-control">
<option value="">Select an item</option>
@foreach (var item in ViewBag.Items)
{
<option value="@item.Id">@item.Name</option>
}
</select>
@section Scripts {
<script>
$(document).ready(function () {
$('#itemDropdown').select2();
});
</script>
}
For multiple ways to bind dropdown lists in ASP.NET MVC, you can refer to
Multiple Ways to Bind Dropdown List in ASP.Net MVC
Step 5: Add Required Scripts
- Ensure you have included the required scripts in your project. You can add them via NuGet Package Manager or include them manually.
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.13/js/select2.min.js" integrity="sha512-2ImtlRlf2VVmiGZsjm9bEyhjGW4dU7B6TNwh/hx/iSByxNENtj3WVE6o/9Lj4TJeVXPi4bnOIMXFIJJAeufa0A==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.13/css/select2.min.css" integrity="sha512-nMNlpuaDPrqlEls3IX/Q56H36qvBASwb3ipuo3MxeWbsQB1881ox0cRv7UPTgBlriqoynt35KjEwgGUeUXIPnw==" crossorigin="anonymous" referrerpolicy="no-referrer" />