In this article I will explain with an example, how to use the jQuery Select2 plugin with Html.DropDownList HTML Helper function in ASP.Net MVC Razor.
The DropDownList will be populated from SQL Server database using Entity Framework in ASP.Net MVC Razor.
jQuery Plugin for Searchable DropDownList
This article makes use of Select2 jQuery Plugin for implementing Searchable DropDownList in ASP.Net MVC Razor.
Database
I have made use of the following table Customers with the schema as follows. CustomerId is an Auto-Increment (Identity) column.
I have already inserted few records in the table.
Note: You can download the database table SQL by clicking the download link below.
Entity Framework Model
Once the Entity Framework is configured and connected to the database table, the Model will look as shown below.
Controller
The Controller consists of the following two Action methods.
Action method for handling GET operation
Inside this Action method, the GetCustomers method is called.
Inside the GetCustomers method, the records are fetched from the Customers table using Entity Framework and are copied into Generic list of SelectListItem class.
Note: The SelectListItem class which is an in-built ASP.Net MVC class. It has all the properties needed for populating a DropDownList.
A Blank item is inserted at first position (0th index) in the Generic list of SelectListItem class and it will be used to show the Default item in DropDownList.
Action method for handling POST operation
This Action method handles the call made from the POST function from the View.
When the Form is submitted, the posted values are captured through the ddlCustomers parameter which is also set as the Name of the DropDownList.
Then the GetCustomers method is called and the selected Customer is fetched using Lambda expression.
Finally, the Name and ID values of the selected Customer are set into a ViewBag object which will be later displayed in View using JavaScript Alert Message Box.
public class HomeController : Controller
{
// GET: Home
public ActionResult Index()
{
List<SelectListItem> customerList = GetCustomers();
return View(customerList);
}
[HttpPost]
public ActionResult Index(string ddlCustomers)
{
List<SelectListItem> customerList = GetCustomers();
if (!string.IsNullOrEmpty(ddlCustomers))
{
SelectListItem selectedItem = customerList.Find(p => p.Value == ddlCustomers);
ViewBag.Message = "Name: " + selectedItem.Text;
ViewBag.Message += "\\nID: " + selectedItem.Value;
}
return View(customerList);
}
private static List<SelectListItem> GetCustomers()
{
CustomersEntities entities = new CustomersEntities();
List<SelectListItem> customerList = (from p in entities.Customers.AsEnumerable()
select new SelectListItem
{
Text = p.Name,
Value = p.CustomerId.ToString()
}).ToList();
//Add Default Item at First Position.
customerList.Insert(0, new SelectListItem { Text = "--Select Customer--", Value = "" });
return customerList;
}
}
View
Inside the View, in the very first line Generic list of SelectListItem class is declared as Model for the View.
Form
The View consists of an HTML Form which has been created using the Html.BeginForm method with the following parameters.
ActionName – Name of the Action. In this case the name is Index.
ControllerName – Name of the Controller. In this case the name is Home.
FormMethod – It specifies the Form Method i.e. GET or POST. In this case it will be set to POST.
The Form consists of a DropDownList and a Submit Button.
DropDownList
The DropDownList is generated using the Html.DropDownList Html Helper method.
The first parameter is the Name of the DropDownList, the same will also be used to fetch the selected value of the DropDownList inside Controller when the Form is submitted.
The second parameter is the Model class for populating the DropDownList i.e. its source of data.
Form Submission
When the Submit Button is clicked, the Form gets submitted and the Name and ID values of the selected Customer is sent to the Controller.
Finally, the Name and ID values of the selected Customer are displayed using JavaScript Alert Message Box.
Select2 jQuery Plugin implementation
First, the jQuery and the JS and CSS files of the jQuery Select2 plugin are inherited.
Then inside the jQuery document ready event handler, the jQuery Select2 plugin is applied to the DropDownList.
@model List<SelectListItem>
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width"/>
<title>Index</title>
</head>
<body>
@using (Html.BeginForm("Index", "Home", FormMethod.Post))
{
@Html.DropDownList("ddlCustomers", Model)
<br/>
<br/>
<input type="submit" value="Submit"/>
}
@if (ViewBag.Message != null)
{
<script type="text/javascript">
window.onload = function () {
alert("@ViewBag.Message");
};
</script>
}
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/select2@4.0.13/dist/css/select2.min.css"/>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript" src="https://cdn.jsdelivr.net/npm/select2@4.0.13/dist/js/select2.min.js"></script>
<script type="text/javascript">
$(function () {
$("#ddlCustomers").select2();
});
</script>
</body>
</html>
Screenshot
Downloads