This article I will explain with an example, how to implement
Select2 DropDownList using
jQuery AJAX in ASP.Net Core (.Net Core 7) MVC.
Select2 plugin
Please refer the following link for documentation for the
jQuery Select2 plugin
Database
I have made use of the following table Customers with the schema as follows.
I have already inserted few records in the table.
Note: You can download the database table SQL by clicking the download link below.
Model
The Model class consists of following properties.
public class Customer
{
[Key]
public int CustomerId { get; set; }
public string Name { get; set; }
}
Database Context
Once the
Entity Framework is configured and connected to the database table, the Database Context will look as shown below.
using Microsoft.EntityFrameworkCore;
namespace MultiSelect_DropDown_jQuery_MVC_Core
{
public class DBCtx : DbContext
{
public DBCtx(DbContextOptions<DBCtx> options) : base(options)
{
}
public DbSet<CustomerModel> Customers { get; set; }
}
}
Controller
The Controller consists of following Action methods.
Action method for handling GET operation
Inside this Action method, simply the View is returned.
Action method for handling jQuery AJAX operation
This Action method handles the call made from the
jQuery AJAX function from the View.
Note: The following Action method handles
AJAX calls and hence the return type is set to
JsonResult.
This method accepts the value of the INPUT TextBox from the View as parameter.
Then, a Generic List of
CustomerModel class object is created based on the TextBox value the related Customers
Name are fetched using
Entity Framework and returned as
JSON result.
Action method for handling POST operation
The Action method accepts CustomerModel class object as parameter.
Inside this Action method, the
Name and
CustomerId values of the selected
Customer are fetched using
EntityFramework and set into a
ViewBag object which will be later displayed used in View for displaying
JavaScript Alert
MessageBox.
public class HomeController : Controller
{
private DBCtx Context { get; }
public HomeController(DBCtx _context)
{
this.Context = _context;
}
public IActionResult Index()
{
return View();
}
[HttpGet]
public JsonResult GetCustomers(string searchTerm)
{
List<CustomerModel> data = this.Context.Customers.Where(c => c.Name.ToUpper().Contains(searchTerm)).ToList();
return new JsonResult(data);
}
[HttpPost]
public IActionResult Index(CustomerModel model)
{
CustomerModel customer = this.Context.Customers.ToList().Find(p => p.CustomerId == model.CustomerId);
ViewBag.Message += "Name: " + customer.Name;
ViewBag.Message += "\\nID: " + customer.CustomerId;
return View(customer);
}
}
View
HTML Markup
Inside the View, the ASP.Net TagHelper is inherited and CustomerModel class is declared as model for the View.
The View consists of an HTML Form which has been created using the following TagHelpers attributes.
asp-action – Name of the Action. In this case the name is Index.
asp-controller – Name of the Controller. In this case the name is Home.
method – 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.
Implementing Select2 DropDownList plugin
Inside the HTML Markup, the following CSS script file is inherited.
1. select2.min.css
Then, the following script files are inherited.
1. jquery.min.js
2. select2.min.js
Inside the
jQuery document ready event handler, the
select2 plugin is applied to the HTML SELECT element.
Properties:
minimumInputLength – it defines the minimum number of characters the user must type before a search is performed.
Then, a
jQuery AJAX call is made to the
GetCustomers Action method and serach item is sent to the server.
Event Handlers:
processResults – When response is get from server, this event handler is triggered. This event handler processes the response from Action result method before displaying it in the dropdown.
Submitting the Form
When the Submit Button is clicked, the Form gets submitted and the CustomerId of the selected Customer is sent to the Controller.
Finally, the
Name and
ID value of the selected
Customer is displayed using
JavaScript Alert
MessageBox.
@addTagHelper*, Microsoft.AspNetCore.Mvc.TagHelpers
@model MultiSelect_DropDown_jQuery_MVC_Core.Models.CustomerModel
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index</title>
</head>
<body>
<form method="post" asp-controller="Home" asp-action="Index">
Name:
<select id="ddlCustomers" asp-for="CustomerId" style="width:300px"></select>
<br />
<br />
<input type="submit" value="Submit" />
@if (ViewBag.Message != null)
{
<script type="text/javascript">
window.onload = function () {
alert("@ViewBag.Message");
};
</script>
}
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
<link href="https://cdn.jsdelivr.net/npm/select2@4.0.13/dist/css/select2.min.css" rel="stylesheet"/>
<script src="https://cdn.jsdelivr.net/npm/select2@4.0.13/dist/js/select2.min.js"></script>
<script type="text/javascript" >
$(function () {
$('#ddlCustomers').select2({
minimumInputLength: 1,
ajax: {
url: '/Home/GetCustomers',
dataType: 'json',
data: function (params) {
return { searchTerm: params.term }
},
processResults: function (data) {
return {
results: $.map(data, function (item) {
return {
id: item.CustomerId,
text: item.Name
};
})
};
}
}
});
});
</script>
</form>
</body>
</html>
Screenshot
Demo
Downloads